我寫了下面的程序來測試時,拷貝構造函數被調用,當賦值運算符稱爲:拷貝構造函數和賦值運算符
#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線,使其更容易理解):
[email protected]:~$ ./test This is the default ctor This is the copy ctor This is the dtor This is the dtor This is the default ctor This is the copy ctor This is the dtor This is the dtor This is the default ctor This is the default ctor This is the assignment operator This is the dtor This is the dtor
如預期的第二組和第三組的行爲,但在第一組複製CONSTRU即使使用賦值運算符,也會調用ctor。
是C++標準,或只是一個聰明的編譯器優化(我用gcc 4.4.1)