复制构造函数和赋值运算符 [英] Copy constructors and Assignment Operators
问题描述
我编写了以下程序来测试何时调用复制构造函数以及何时调用赋值运算符:
I wrote the following program to test when the copy constructor is called and when the assignment operator is called:
#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行以使其更易于理解):
This results in the following output (just added empy lines to make it more understandable):
doronw@DW01:~$ ./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
第二和第三组的行为与预期的一样,但是在第一组中,即使使用了赋值运算符,也会调用复制构造函数。
The second and third set behave as expected, but in the first set the copy constructor is called even though the assignment operator is used.
此行为是C ++标准的一部分,还是仅仅是聪明的编译器优化(我正在使用gcc 4.4.1)
Is this behaviour part of the C++ standard or just a clever compiler optimization (I am using gcc 4.4.1)
推荐答案
在第一个测试用例中不使用赋值运算符。它仅使用称为复制初始化的初始化形式。初始化对象时,复制初始化不考虑显式构造函数。
No assignment operator is used in the first test-case. It just uses the initialization form called "copy initialization". Copy initialization does not consider explicit constructors when initializing the object.
struct A {
A();
// explicit copy constructor
explicit A(A const&);
// explicit constructor
explicit A(int);
// non-explicit "converting" constructor
A(char const*c);
};
A a;
A b = a; // fail
A b1(a); // succeeds, "direct initialization"
A c = 1; // fail, no converting constructor found
A d(1); // succeeds
A e = "hello"; // succeeds, converting constructor used
在与隐式转换相对应的情况下使用复制初始化,其中不会像函数参数传递和从函数返回那样显式启动转换。
Copy initialization is used in those cases that correspond to implicit conversions, where one does not explicitly kick off a conversion, as in function argument passing, and returning from a function.
这篇关于复制构造函数和赋值运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!