复制构造函数是否调用默认构造函数来创建对象

时间:2015-10-23 12:35:49

标签: c++

复制构造函数在C ++中创建对象时是否调用默认构造函数?如果我隐藏默认构造函数,我仍然可以创建副本,对吧?

2 个答案:

答案 0 :(得分:1)

删除默认构造函数不会阻止您复制对象。当然,你需要一种方法来生成对象,即你需要提供一个非默认的构造函数。

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;
}

Demo 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;
};

Demo 2.

答案 1 :(得分:1)

答案是否。

通过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
}
相关问题