开发者

Is it allowed to assign to a dereferenced this (*this)?

开发者 https://www.devze.com 2023-01-20 07:43 出处:网络
I\'m currently refreshing my C++ skills and was wondering if it is possible to assign something to *this.

I'm currently refreshing my C++ skills and was wondering if it is possible to assign something to *this. I know assigning to this is forbidden, but can't find the same information for my case.

An example:

c开发者_JS百科lass Foo {
  int x;
public:
  Foo(int x) : x(x) {}
  Foo incr() { return Foo(x+1); }
  void incr_() { (*this) = incr(); }
};

Edit: corrected incr()'s return type from void to Foo.


Yes, it is allowed, and it actually invokes your class' assignment operator.


void incr() { return Foo(x+1); }

This is invalid. You cannot return a Foo object from a function having void return type.

void incr_() { 

   (*this) = incr(); // This invokes Foo& operator = (const Foo& ) (compiler synthesized)
}

This is fine.


Yes, it works. And *this = x is just syntactic sugar for operator=(x).


Yes, you can, if *this return value is of a datatype that has an assignment operator defined.

0

精彩评论

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