C++ 复制构造函数和赋值运算符
我编写了以下程序来测试何时调用复制构造函数以及何时调用赋值运算符:C++ 复制构造函数和赋值运算符,c++,copy-constructor,C++,Copy Constructor,我编写了以下程序来测试何时调用复制构造函数以及何时调用赋值运算符: #include class Test { public: Test() : iItem (0) { std::cout << "This is the default ctor" << std::endl; } Test (const Test& t) : iItem (t.iItem) {
#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;
}
}
#包括
课堂测试
{
公众:
Test():
项目(0)
{
STD::CUT< P>在第一个测试用例中没有使用赋值操作符。它只使用初始化形式,称为“复制初始化”。初始化初始化时,复制初始化不考虑显式构造函数。
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
复制初始化用于对应于隐式转换的情况,其中没有显式地启动转换,如函数参数传递,从函数返回。
< P>第一个集合是根据C++标准,而不是由于某些优化。
第12.8节([class.copy]
)给出了一个类似的示例:
class X {
// ...
public:
X(int);
X(const X&, int = 1);
};
X a(1); // calls X(int);
X b(a, 0); // calls X(const X&, int);
X c = b; // calls X(const X&, int);
最后一行将与您的案例相匹配。C++标准8.5/12
在中发生的初始化
参数传递,函数返回,
抛出异常(15.1),处理
例外情况(15.3),以及
括号内的初始值设定项列表
(8.5.1)称为复制初始化
与形式相同
T x = a;
T x(a);
在新数据库中发生的初始化
表达式(5.3.4),静态
表达式(5.2.9),函数式
符号类型转换(5.2.3),以及
基础和成员初始值设定项(12.6.2)
称为直接初始化,是
等价于形式
T x = a;
T x(a);