Prior to writing the copy constructor, the parameter is referenced and not passed for the value, just to reduce the memory copy. Today, however, I see an article that finds that it is wrong to understand the parameters of the copy construction. The argument is a reference and is not passed as a value to prevent infinite recursion of the copy constructor, resulting in a stack overflow.
Let's look at an example:
class test
{
public:
test()
{
cout << "constructor with argument\n";
}
~test()
{
}
test(test& t)
{
cout << "copy constructor\n";
}
test&operator=(const test&e)
{
cout << "assignment operator\n";
return *this;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
test ort;
test a(ort);
test b = ort ;
a = b;
return 0;
}
Output: If you can understand this knowledge. Let's explain why value passing is infinitely recursive! If the copy constructor is this:
test(test t);
We call
test ort;
test a(ort); --> test.a(test t=ort)==test.a(test t(ort))
-->test.a(test t(test t = ort))
==test.a(test t(test t(ort)))
-->test.a(test t(test t(test t=ort)))
- ...
就这样会一直无限递归下去。
Here we also understand why the parameters of a copy constructor must be a reference and cannot be passed for a value. Next, we test the parameters of the assignment constructor, and if we change its parameters to a value pass, do a test.
class test
{
public:
test()
{
cout << "constructor with argument\n";
}
~test()
{
}
test(test& t)
{
cout << "copy constructor\n";
}
test&operator=(test e)
{
cout << "assignment operator\n";
return *this;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
test ort;
test a(ort);
test b = ort ;
a = b;
return 0;
}
Output: Assignment constructor If it is passed as a value, it is only one copy more, and does not have infinite recursion.Summary: The parameters of the copy constructor must be references. An assignment constructor parameter can be either a reference or a value pass, and a value pass will be copied more than once. Therefore, it is recommended that the assignment constructor also be written as a reference type. (Ckk see just now I understand still have deviation: Left and right value is not the key, reduce copy number increase assignment efficiency is the focus)
Why does the C + + copy constructor parameter have to be a reference? Must the assignment constructor argument also be a reference?