开发者

why assignment operator returns ref not pointer?

开发者 https://www.devze.com 2023-03-29 20:56 出处:网络
I saw some q&a on SO about the Big-Three and copy-and-swap. Ind开发者_运维知识库eed, I learned some new stuff, but there\'s one thing I don\'t quite understand.

I saw some q&a on SO about the Big-Three and copy-and-swap. Ind开发者_运维知识库eed, I learned some new stuff, but there's one thing I don't quite understand.

Why does the operator= return a reference not a pointer?


There's nothing preventing you from returning a pointer if you'd like (though, I don't see why), but if you want to mimick the behaviour of the integral types in c++ you return a reference.


Why should it, what good would a pointer be? Returning a reference allows you to say x = y = z; which a pointer wouldn't, and generally lets you use x = y as an lvalue of the same type as x.

You're free to overload any assignment operator you like, but the standard practice of returning a reference to the object itself is very useful.


The assignment operator sets the operators left hand side equal to its right hand side, so conceptually the types of lhs and rhs should match. If your assignment operator takes a reference as its parameter, it ought to return a reference:

Foo &operator=(const Foo &f);

It would be downright weird to write:

Foo *operator=(const Foo &f);   // this is weird because type of lhs != type of rhs

Now, you could provide a version of operator=() that assigns one Foo* to another:

Foo *operator=(const Foo *f);

but the "big three" or "rule of three" doesn't say anything about assigning pointers. The "rule" says that if you override any of {destructor, assignment operator, copy constructor}, you'll probably need to override all of them because they should all deal with the same set of ivars. But that's when you're assigning one object to another. Assigning one pointer to another is usually the same no matter the type of the pointer.

Think what would happen if you used the Foo* version of the assignment operator in place of the reference version: you'd have no way to set two pointers to point to the same object.


Returning a pointer would mean that instead of writing

a = b = c;

you would have to write

*(a = b) = c;

which is ugly and also contrdicts normal C/C++ usage.

0

精彩评论

暂无评论...
验证码 换一张
取 消