在我的这个问题中,@DeadMG 说通过this
指针重新初始化一个类是未定义的行为。在某处的标准中是否有提及?
例子:
#include <iostream>
class X{
int _i;
public:
X() : _i(0) { std::cout << "X()\n"; }
X(int i) : _i(i) { std::cout << "X(int)\n"; }
~X(){ std::cout << "~X()\n"; }
void foo(){
this->~X();
new (this) X(5);
}
void print_i(){
std::cout << _i << "\n";
}
};
int main(){
X x;
x.foo();
// mock random stack noise
int noise[20];
x.print_i();
}
Ideone 的示例输出(我知道 UB 也可以是“看似正确的行为”)。
请注意,我没有在类之外调用析构函数,以不访问生命周期已结束的对象。另请注意,@DeadMG 表示直接调用析构函数是可以的,只要它为每个构造函数调用一次。