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)
operator=是合法的并且可以按预期工作,但是在班级不动的情况下,将创建一个不必要的临时调用。因此,手动分配默认值可能会更有效,如果要扩展该类,则默认值将很麻烦且容易出错。*this = Foo(),如果允许的话,可能会更有效,因为我假设复制省略在这里可以工作(不管类是否可移动)。所以我的问题是:
*this = Foo();合法吗?如果是,请提供标准参考Foo是可移动的。(如果您认为这是骗子,请找我正确的问题,我什么也找不到)
- 声明
*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
Foois movable.- In case it's not.
There are no differences regarding efficiency. Copy elision will be taken by any decent modern c++ compiler.
| 归档时间: |
|
| 查看次数: |
157 次 |
| 最近记录: |