是* this = Ctor(); 清除对象状态是否合法有效?

and*_*eee 4 c++ constructor this-pointer language-lawyer c++17

我偶然发现了这段代码来重新建立类不变式:

class Foo {
  // some stuff in here
public:
  void clear() {
    *this = Foo();
    //operator=(Foo()); // commented out in favor of the line above
  }
};
Run Code Online (Sandbox Code Playgroud)
  • 我假设对class的调用operator=是合法的并且可以按预期工作,但是在班级不动的情况下,将创建一个不必要的临时调用。因此,手动分配默认值可能会更有效,如果要扩展该类,则默认值将很麻烦且容易出错。
  • *this = Foo(),如果允许的话,可能会更有效,因为我假设复制省略在这里可以工作(不管类是否可移动)。

所以我的问题是:

  • 声明*this = Foo();合法吗?如果是,请提供标准参考
  • 有什么更有效的方法(假设第一个要点是正确的)?
    • 万一Foo是可移动的。
    • 万一不是。

(如果您认为这是骗子,请找我正确的问题,我什么也找不到)

πάν*_*ῥεῖ 7

  • 声明*this = Foo();合法吗?如果是,请提供标准参考

没错。遵循可以通过取消引用的指针分配值的标准。

I don't think we can find anything in the c++-standard mentioning the situation, since it's not a special situation as you think it is.
Assigning a dereferenced *this pointer works as with any other pointer.

  • What is more efficient (providing that the first bullet point is true)?
    • In case Foo is movable.
    • In case it's not.

There are no differences regarding efficiency. Copy elision will be taken by any decent modern c++ compiler.

  • 我相信复制删除的机会微乎其微。如果构造函数抛出异常,则“ * this”不应更改状态。因此,必须首先构造新的“ Foo”实例,然后进行分配。如果没有移动分配运算符,您如何取消副本?也许如果构造是`noexcept`,`* this`可以先被销毁再构造。 (2认同)