what is return type of assignment operator?

China☆狼群 提交于 2019-11-27 01:01:36

The standard correctly defines the return type of an assignment operator. Actually, the assignment operation itself doesn't depend on the return value - that's why the return type isn't straightforward to understanding.

The return type is important for chaining operations. Consider the following construction: a = b = c;. This should be equal to a = (b = c), i.e. c should be assigned into b and b into a. Rewrite this as a.operator=(b.operator=(c)). In order for the assignment into a to work correctly the return type of b.operator=(c) must be reference to the inner assignment result (it will work with copy too but that's just an unnecessary overhead).

The dereference operator return type depends on your inner logic, define it in the way that suits your needs.

They can both be anything, but usually operator = returns the current object by reference, i.e.

A& A::operator = ( ... )
{
   return *this;
}

And yes, "reference to the type of left hand operand" and "lvalue referring to left hand operand" mean the same thing.

The dereference operator can have basically any return type. It mostly depends on the logic of the program, because you're overloading the operator that applies to an object, not to a pointer to the object. Usually, this is used for smart pointers, or iterators, and return the object they wrap around:

struct smart_ptr
{
   T* innerPtr;
   T* smart_ptr::operator* ()
   {
      return innerPtr;
   }
}

smart_ptr p; 
T* x = *p;  

I have seen similar issues, but I guess it would be best to use

X& X::operator=(const X&);

Using this, you will be able to reuse the object in a chain-assignment.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!