8
#include <stdlib.h>
#include <iostream>
#include <vector>
#include <string>
class A
{
public:
    std::string s;
    A()
    {
        s = "string";
        new(this)A(*this);
    }
};
int main()
{
    A a;
    std::cout<<a.s;
    return 0;
}

我在输出中得到空字符串。C++ 标准对这种行为有什么看法?

4

2 回答 2

4

这里必须至少有两个问题:

  • 您尝试使用自身的副本初始化 A
  • 在构造函数内部, A 尚未完全构造,因此您无法真正复制它

更不用说这new(this)本身就是可疑的。

于 2012-03-19T11:01:48.230 回答
0

通过这样做,您连续两次调用s' 的构造函数,因此,行为是未定义的(并且很可能会泄漏一些内存)。

于 2012-03-19T12:16:39.807 回答