【发布时间】:2013-01-04 13:50:05
【问题描述】:
可能重复:
What are copy elision and return value optimization?
why isn’t the copy constructor called
为什么在下面的代码中 gcc 和 clang 都不调用 A 类的复制构造函数,甚至一个 时间(只有一个对象被创建,因为析构函数只被调用一次)。
class A
{
public:
explicit A()
{
std::cout << "A()" << std::endl;
}
A(const A& toCp)
{
std::cout << "A(const A&)" << std::endl;
}
~A()
{
std::cout << "~A()" << std::endl;
}
A& operator=(const A& toCp)
{
std::cout << "A::operator=" << std::endl;
}
};
A fun()
{
A x;
std::cout << "fun" << std::endl;
return x;
}
int main()
{
A u = fun();
return 0;
}
这段代码的打印输出是:
A()
fun
~A()
我认为它应该调用 2 次复制构造函数(一次用于返回值,一次用于行内A u = fun(7);
我在这段代码中使用了 gcc 和带有 -O0 的 clang。
有什么想法吗?
【问题讨论】:
-
Copy elision 尝试将
-fno-elide-constructors传递给 GCC。