可能重複:
Why copy constructor is not called in this case?複製構造不調用
考慮下面的示例程序:
#include <iostream>
using namespace std;
class sample
{
private:
int x;
public:
sample(int a=0) : x(a)
{
cout << "default ctor invoked\n";
}
sample(const sample& obj)
{
cout << "copy ctor invoked\n";
}
};
int main()
{
sample s2 = sample(20); //Line1
sample s3 = 20; //Line2
return 0;
}
在Line1
,第一sample
類的構造函數被調用explicitly
與參數20.然後我的預期要調用的複製構造函數來初始化s2。
在Line2中,首先使用參數20首先調用sample
類的構造函數implicitly
。這裏我也希望調用copy構造函數來初始化s2。
在這兩種情況下,複製構造函數都不會被調用?這是爲什麼發生?我相信,我對複製構造函數的調用有所瞭解。有人能糾正我在哪裏出錯嗎?
這是預期的 - 讓我試試並找到一個好例子 – 2012-01-10 04:42:14
在某些情況下,可以省略對複製構造函數的調用。 – 2012-01-10 04:45:12
@ R.MartinhoFernandes:在某些情況下。但s2和s3必須以某種方式初始化。如何在沒有調用copy ctor的情況下完成? – 2012-01-10 04:46:16