![](/img/trans.png)
[英]why the copy constructor is called twice when the object is contained in another object in c++?
[英]When is a copy constructor called in c++, is not it called when I assign a object to another object?
class Myinteger(){
public:
Myinteger( int len ); // simple constructor
Myinteger( const Myinteger &obj); // copy constructor
~Myinteger(); // destructor
private:
int *ptr;
}
Myinteger::Myinteger(const Myinteger &obj) {
cout << "Copy constructor allocating ptr." << endl;
ptr = new int;
*ptr = *obj.ptr; // copy the value
}
int main(){
Myinteger obj1(10);
Myinteger obj2(20);
obj1=obj2;
return 0;
}
將obj2分配給obj1時,不會調用復制構造函數,因為“復制構造函數分配ptr”,所以我確認了這一點。 沒有打印到控制台,
因此,如果在將obj2分配給obj1的情況下,如果未調用復制構造函數,則在上述情況下將調用哪個方法,還應說明在哪種情況下調用了類的復制構造函數。
復制構造函數,例如將這樣聲明:
Myinteger(const Myinteger& other);
將用作
Myinteger obj2 = obj1;
要么
Myinteger obj2(obj1);
但是一個賦值運算符,聲明為:
Myinteger& operator =(const Myinteger& other);
將用於您的代碼有
Myinteger obj2;
obj2 = obj1;
這就是代碼中的內容,因此將調用賦值運算符,而不是復制構造函數。
在此聲明中
obj1=obj2;
使用復制賦值運算符是因為賦值的兩個操作數(對象)均已創建。 因此,如果已經創建它們,則不會調用任何構造函數。
如果要使用復制構造函數,則可以編寫例如
int main()
{
Myinteger obj1( "10" );
Myinteger obj2 = obj1;
return 0;
}
我得到了答案,我以為只要我們將一個對象分配給另一個在概念上是錯誤的對象,就會調用復制構造函數。 僅當創建對象時才調用copy構造函數,如果我們將對象分配給已存在的對象,則將調用重載的賦值運算符函數,否則從類中調用默認的賦值運算符函數。
我得到了答案,我以為每當我們將一個對象分配給另一個在概念上是錯誤的對象時,就會調用復制構造函數。 僅當創建對象時才調用copy構造函數,如果我們將對象分配給已存在的對象,則將調用重載的賦值運算符函數,否則從類中調用默認的賦值運算符函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.