在C ++中创建对象时,复制构造函数是否调用默认构造函数?如果我隐藏了默认构造函数,我仍然应该能够创建副本,对吗?
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
}
删除默认构造函数并不会阻止你复制对象。当然,你需要一种方法来首先生成对象,也就是说,你需要提供一个非默认构造函数。
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;
}
当您编写自己的复制构造函数时,应将调用路由到带参数的适当构造函数,如下所示:
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;
};