问题
There is a part of C++ code I don't really understand. Also I don't know where should I go to search information about it, so I decided to ask a question.
#include <iostream>
#include <string>
using namespace std;
class Test
{
public:
Test();
Test(Test const & src);
Test& operator=(const Test& rhs);
Test test();
int x;
};
Test::Test()
{
cout << "Constructor has been called" << endl;
}
Test::Test(Test const & src)
{
cout << "Copy constructor has been called" << endl;
}
Test& Test::operator=(const Test& rhs)
{
cout << "Assignment operator" << endl;
}
Test Test::test()
{
return Test();
}
int main()
{
Test a;
Test b = a.test();
return 0;
}
Why the input I get is
Constructor has been called
Constructor has been called
? a.test() creates a new instance by calling "Test()" so that's why the second message is displayed. But why no copy constructor or assignment called? And if I change "return Test()" to "return *(new Test())" then the copy constructor is called.
So why isn't it called the first time?
回答1:
Compilers are very smart. Both copies - returning from test
and initialising b
(not this is not an assignment) - are elided according to the following rule (C++11 §12.8):
when a temporary class object that has not been bound to a reference (12.2) would be copied/moved to a class object with the same cv-unqualified type, the copy/move operation can be omitted by constructing the temporary object directly into the target of the omitted copy/move
Compilers are allowed to do this even if it would change the behaviour of your program (like removing your output messages). It's expected that you do not write copy/move constructors and assignment operators that have other side effects.
Note that is only one of four cases in which copy elision can occur (not counting the as-if rule).
回答2:
The call to a.test() returns by value and this value is then assigned to b "copying" the return value. This invokes the copy constructor.
来源:https://stackoverflow.com/questions/20874193/c-copy-constructor-behaviour