why overloading assignment have to return reference instead of value?
Well, consider the semantics of assignment.
X a(0);
X b(42);
a = b;
should the last line create a new temporary X
object? I can't think why you'd want it to, but that would be the effect of operator=
returning a value.
So why does it return a reference at all? Because built-in types have these assignment semantics:
ssize_t rc;
if ((rc = write(fd, buf, sz)) != sz) {
// handle error
}
that is, you can use the value of an assignment expression in an outer expression. The value is the same as the value of the left-hand-side after the assignment. How do you get the same behaviour for user-defined types?
For a motivating example, consider
std::vector<int> v;
if ((v = make_huge_vector()).empty()) {
// it's not supposed to be empty
}
Would it be reasonable for this to create a redundant temporary copy of the (hopefully) massive vector?
"*this" will be represented as dereference
When you dereference a pointer-to-object, you get a reference to the object. Otherwise, again, dereferencing a pointer would have to create a temporary copy of the object. Consider:
X *x = new X;
x->init();
is the same as
(*x).init();
should we be initializing a copy of the object pointed to by x
? We'd never be able to initialize the allocated object. So, the only sane thing for (*x)
to evaluate to, is a reference to the object.