在其他构造函数中调用复制构造函数
invoking copy constructor inside other constructor
#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
的构造函数,因此,行为是未定义的(并且很可能一些内存被泄露了(。
相关文章:
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 当从函数参数中的临时值调用复制构造函数时
- 如果有一个模板构造函数只有一个泛型参数,为什么我必须有一个复制构造函数
- 使用复制构造函数复制双精度数组
- C 无可行的构造函数复制类型的变量
- 没有可行的构造函数复制类型 'MyString' 的数组元素
- 编译时,复制构造函数/复制分配和正常功能调用优化之间是否存在任何区别
- 如何最小化调用列表构造函数(复制构造函数)的次数?
- C 11矢量构造函数复制与范围
- 我定义了一个非复制构造函数;复制构造函数还会被隐式定义吗
- 可以将构造函数复制为转换运算符
- 将基类指针的构造函数复制到子类
- C++树类:构造函数/复制/内存泄漏
- 如何制作这个在模板构造函数复制中使用类型定义的类型的模板
- 将构造函数复制为模板化的成员函数
- 绕过私有复制构造函数/复制赋值C++
- C++通过构造函数复制对象
- 复制构造函数 - 复制C++中的对象
- 将带unique_ptr的类的构造函数复制到作为成员的抽象类