在其他构造函数中调用复制构造函数

invoking copy constructor inside other constructor

本文关键字:构造函数 复制 调用 其他      更新时间:2023-10-16
#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++标准对这种行为有什么看法?

这里至少要有两个问题:

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

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

你这样做连续

两次调用s的构造函数,因此,行为是未定义的(并且很可能一些内存被泄露了(。