簡體   English   中英

復制構造函數是否調用默認構造函數來創建對象

[英]Does copy constructor call default constructor to create an object

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

演示 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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM