在C++中创建对象时,复制构造函数是否调用默认构造函数?如果我隐藏默认构造函数,我应该仍然能够创建副本,对吗?
发布于 2015-10-23 12:52:30
删除默认构造函数并不会阻止您复制对象。当然,首先您需要一种方法来生成对象,即您需要提供一个非默认的构造函数。
struct Demo {
Demo() = delete;
Demo(int _x) : x(_x) { cout << "one-arg constructor" << endl; }
int x;
};
int main() {
Demo a(5); // Create the original using one-arg constructor
Demo b(a); // Make a copy using the default copy constructor
return 0;
}
演示1。
编写自己的复制构造函数时,应该将调用路由到具有参数的适当构造函数,如下所示:
struct Demo {
Demo() = delete;
Demo(int _x) : x(_x) { cout << "one-arg constructor" << endl; }
Demo(const Demo& other) : Demo(other.x) {cout << "copy constructor" << endl; }
int x;
};
演示2。
发布于 2019-03-28 08:16:31
答案是否定的。
对象内存的创建是通过new
指令完成的。然后,复制构造函数负责实际的复制(显然,只有当它不是浅层副本时才相关)。
如果需要,可以在复制构造函数执行之前显式调用不同的构造函数。
您可以很容易地通过复制/粘贴这段代码并运行它来测试它.
#include <stdio.h>
class Ctest
{
public:
Ctest()
{
printf("default constructor");
}
Ctest(const Ctest& input)
{
printf("Copy Constructor");
}
};
int main()
{
Ctest *a = new Ctest(); //<-- This should call the default constructor
Ctest *b = new Ctest(*a); //<-- this will NOT call the default constructor
}
https://stackoverflow.com/questions/33302513
复制相似问题