是否可以分配给解除引用的这个(*this)?

Kol*_*lja 8 c++

我目前正在刷新我的C++技能,并想知道是否可以分配一些东西*this.我知道分配this是禁止的,但是我的案例找不到相同的信息.

一个例子:

class Foo {
  int x;
public:
  Foo(int x) : x(x) {}
  Foo incr() { return Foo(x+1); }
  void incr_() { (*this) = incr(); }
};
Run Code Online (Sandbox Code Playgroud)

编辑:修正incr()从的返回类型voidFoo.

Pra*_*rav 2

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

这是无效的。Foo您不能从具有返回类型的函数返回对象void

void incr_() { 

   (*this) = incr(); // This invokes Foo& operator = (const Foo& ) (compiler synthesized)
}
Run Code Online (Sandbox Code Playgroud)

这可以。

  • IMO,这更适合作为评论而不是答案。 (3认同)