Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/160.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在其他构造函数中调用复制构造函数 #包括 #包括 #包括 #包括 甲级 { 公众: std::字符串s; () { s=“字符串”; 新(本)A(*本); } }; int main() { A A; std::cout_C++_Placement New - Fatal编程技术网

C++ 在其他构造函数中调用复制构造函数 #包括 #包括 #包括 #包括 甲级 { 公众: std::字符串s; () { s=“字符串”; 新(本)A(*本); } }; int main() { A A; std::cout

C++ 在其他构造函数中调用复制构造函数 #包括 #包括 #包括 #包括 甲级 { 公众: std::字符串s; () { s=“字符串”; 新(本)A(*本); } }; int main() { A A; std::cout,c++,placement-new,C++,Placement New,这里至少有两个问题: 您尝试使用自身的副本初始化 在构造函数中,A尚未完全构造,因此无法真正复制它 更不用说new(this)本身是可疑的。您这样做是在连续两次调用s的构造函数,因此,行为是未定义的(很可能一些内存泄漏)。Auwgh,我现在真的需要一些咖啡。我在GCC4.5的输出中得到了“string”是:new(this)a(*this)在其他构造函数中调用复制构造函数?stdlib.h=>cstdlib但是这里的头是不必要的。可能重复的new(this)是可以的。并且通常也可以保证使用自

这里至少有两个问题:

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

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

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

Auwgh,我现在真的需要一些咖啡。我在GCC4.5的输出中得到了“string”是:
new(this)a(*this)
在其他构造函数中调用复制构造函数?
stdlib.h
=>
cstdlib
但是这里的头是不必要的。可能重复的
new(this)
是可以的。并且通常也可以保证使用自身副本分配给某个对象(复制赋值运算符需要防止自赋值)–另一方面,复制构造是另一回事。@Konrad:那么默认(生成的)复制构造函数防止自赋值,因此不会执行实际复制?似乎中间变量a(*this);new(this)(a);解决了“问题”?@user396672没有这种情况。默认的复制赋值运算符可以防止自赋值。我认为默认的复制构造函数不会这样做,因为这种情况通常不会发生。
#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;
}