class FooView final : public Something
{
...
void refresh()
{
this->~FooView();
new (this) FooView();
}
}
Run Code Online (Sandbox Code Playgroud)
我从来没有见过这个习语,看起来它可能非常微妙和混乱,但我实际上想不出它有什么问题(只要FooView是最终的)。这是一个坏主意吗?
Gui*_*cot 12
您可以这样做,但如果您有引用或常量成员,或者类的类型发生变化,则需要为此进行内存清洗。
考虑一下:
struct FooView {
const int val;
void refresh()
{
this->~FooView();
new (this) FooView{5};
}
}
int main() {
FooView fv{9};
std::cout << fv.val; // surely 9!
fv.refresh();
std::cout << fv.val; // hmm... val is a const object, so it's 9 still?
}
Run Code Online (Sandbox Code Playgroud)
为了避免这种未定义的行为,您应该使用 清洗内存std::launder。编译器将假设 的生命周期fv不会受到除 之外的任何因素的影响}。清洗将使编译器假设存在一个与以下对象无关的对象fv:
int main() {
FooView fv{9};
std::cout << fv.val; // surely 9!
fv.refresh();
std::cout << std::launder(&fv)->val; // yay, 5
}
Run Code Online (Sandbox Code Playgroud)
现在这是一个好主意吗?我建议不要这样做,因为它可能会导致混乱,但可以安全地完成。