我编写了以下程序来测试何时调用复制构造函数以及何时调用赋值运算符:
#include
class Test
{
public:
Test() :
iItem (0)
{
std::cout << "This is the default ctor" << std::endl;
}
Test (const Test& t) :
iItem (t.iItem)
{
std::cout << "This is the copy ctor" << std::endl;
}
~Test()
{
std::cout << "This is the dtor" << std::endl;
}
const Test& operator=(const Test& t)
{
iItem = t.iItem;
std::cout << "This is the assignment operator" << std::endl;
return *this;
}
private:
int iItem;
};
int main()
{
{
Test t1;
Test t2 = t1;
}
{
Test t1;
Test t2 (t1);
}
{
Test t1;
Test t2;
t2 = t1;
}
}
这会产生以下输出(只是添加了 empy 行以使其更易于理解):
doronw@DW01:~$ ./test 这是默认的ctor 这是复制ctor 这是dtor 这是dtor 这是默认的ctor 这是复制ctor 这是dtor 这是dtor 这是默认的ctor 这是默认的ctor 这是赋值运算符 这是dtor 这是dtor
第二组和第三组按预期运行,但在第一组中,即使使用了赋值运算符,也会调用复制构造函数。
这种行为是 C++ 标准的一部分还是只是一个聪明的编译器优化(我使用的是 gcc 4.4.1)