[英]Why copy constructor is not called here?
對於以下代碼:
#include<iostream>
using namespace std;
class Test
{
public:
Test(const Test &t) { cout<<"Copy constructor called"<<endl;}
Test() { cout<<"Constructor called"<<endl;}
};
Test fun()
{
cout << "fun() Called\n";
Test t;
return t;
}
int main()
{
Test t1;
Test t2 = fun();
return 0;
}
我真的很困惑何時調用復制構造函數? 就像我在運行上面的程序一樣,不會調用復制構造函數。 這意味着如果我搞砸了傳遞給復制構造函數的參數(消除了const關鍵字),它應該不會顯示任何編譯器錯誤。 但是它的表現
“沒有匹配的函數可以調用'Test :: Test(Test)'”
此外,fun()返回的是test類型的對象,該對象是在fun()執行期間創建的。 為什么這里沒有調用復制構造函數?
int main()
{
fun();
return 0;
}
如果我要對主函數進行以下更改,為什么復制構造函數僅被調用一次,而不是兩次?
int main()
{
Test t2 = fun();
Test t3 = t2;
return 0;
}
當我在VS2010中運行您的代碼時,我得到正確的結果:
1。
Constructor called
fun() Called
Constructor called
Copy constructor called
2。
fun() Called
Constructor called
Copy constructor called
3。
fun() Called
Constructor called
Copy constructor called
Copy constructor called
復制構造函數已正確調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.