为什么这种未定义的行为?
struct s
{
const int id; // <-- const member
s(int id):
id(id)
{}
s& operator =(const s& m) {
return *new(this) s(m); // <-- undefined behavior?
}
};
Run Code Online (Sandbox Code Playgroud)
(从标准引用会很好).
这个问题来自于这个答案.
在我的这个问题中,@ 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();
}
Run Code Online (Sandbox Code Playgroud)
Ideone的输出示例(我知道UB也可能是"看似正确的行为").
请注意,我没有在类之外调用析构函数,因为没有访问生命周期结束的对象.另请注意,@ DeadMG表示直接调用析构函数是可以的 - 因为它为每个构造函数调用一次.
在这个答案中,Ryan直接调用虚拟析构函数.我已经在VS2010中测试了代码,它正确地调用了所有析构函数(使用日志记录语句测试).这样做真的有效吗?这种方法有哪些问题,缺陷甚至是好处?
我只能将它视为真正强制重置实际类型的一种方法,即使它们不覆盖虚reset函数,因为它们至少必须在它们的析构函数中清理.
另外,对析构函数的调用会带来什么样的副作用呢?在这样的析构函数调用之后使用该对象是不确定的行为?如果一个人立即通过new (this) MyClass();电话重新初始化该怎么办?
我遇到了一些让我感到恐惧的代码.基本上它遵循这种模式:
class Foo
{
public:
//default constructor
Foo(): x(0), ptr(nullptr)
{
//do nothing
}
//more interesting constructor
Foo( FooInitialiser& init): x(0), ptr(nullptr)
{
x = init.getX();
ptr = new int;
}
~Foo()
{
delete ptr;
}
private:
int x;
int* ptr;
};
void someFunction( FooInitialiser initialiser )
{
int numFoos = MAGIC_NUMBER;
Foo* fooArray = new Foo[numFoos]; //allocate an array of default constructed Foo's
for(int i = 0; i < numFoos; ++i)
{
new( fooArray+ i) Foo( initialiser ); //use …Run Code Online (Sandbox Code Playgroud)