C ++复制构造函数行为 [英] C++ copy constructor behaviour
问题描述
有一部分C ++代码我真的不明白。
我也不知道在哪里搜索关于它的信息,所以我决定提出一个问题。
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;
}
为什么我得到的输入是
Constructor has been called
Constructor has been called
?
a.test()通过调用Test()创建一个新实例,这就是显示第二条消息的原因。但为什么没有复制构造函数或赋值调用?
如果我将return Test()更改为return *(new Test()),那么将调用复制构造函数。
? 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.
它是第一次吗?
推荐答案
编译器非常聪明。两个副本 - 从 test
返回并初始化 b
(不是此分配)当没有被绑定到引用(12.2)的临时类对象将被引用时,规则(C ++ 11§12.8):
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):
复制/移动到具有相同cv非限定类型的类对象,可以通过将临时对象直接构造到省略的复制/移动的目标中来省略复制/移动操作
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.
请注意,这只是可能发生复制删除的四种情况之一不计算as-if规则)。
Note that is only one of four cases in which copy elision can occur (not counting the as-if rule).
这篇关于C ++复制构造函数行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!