可能重复:
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