复制构造函数省略?
不太明白为什么当我使用 VC2010 在调试模式下构建时不调用此复制构造函数.
Don't quite understand why this copy constructor is not invoked when I build with debug mode using VC2010.
class SomeClass
{
public:
SomeClass(int meaningless){}
SomeClass(const SomeClass& sc)
{
cout << "Copy Constructor invoked!" << endl;
}
};
int main()
{
SomeClass test(SomeClass(9999)); // Copy constructor not invoked.
}
我认为这与 RVO 无关,因为我没有返回任何值.
I think this has nothing to do with RVO since I am not returning any values.
更有趣的是,当我将复制构造函数设为私有时,即使省略了复制构造函数,编译器也不会编译.
More interesting, when I make the copy constructor private, the compiler wouldn't even compile even if it omit the copy constructor.
推荐答案
是编译器做的优化.根据语言规范,编译器可以在可能的情况下省略对复制构造函数的调用.
It is an optimization done by the compiler. According to the language specification, the compiler is allowed to omit the call to the copy-constructor whenever it can.
一个可访问的复制构造函数只需要用于语义检查,即使它实际上没有被调用.语义检查是在优化之前完成的.
An accessible copy-constructor is needed for semantic check only, even though it is not actually called. Semantic check is done much before the optimization.
但是,如果您使用-fno-elide-constructors
选项和GCC 编译它,则不会执行复制省略,并且会调用复制构造函数.GCC 文档 说,
However, if you compile it with -fno-elide-constructors
option with GCC, then the copy-elision will not be performed, and the copy-constructor will be called. The GCC doc says,
-fno-elide-constructors
C++ 标准允许实现省略创建临时对象,该临时对象仅用于初始化另一个相同类型的对象.指定此选项会禁用该优化,并强制 G++ 在所有情况下调用复制构造函数.
The C++ standard allows an implementation to omit creating a temporary which is only used to initialize another object of the same type. Specifying this option disables that optimization, and forces G++ to call the copy constructor in all cases.
使用 MSVC10,您可以使用 /Od 根据 MSDN 关闭程序中的所有优化.
With MSVC10, you can use /Od which according to the MSDN turns off all optimizations in the program.
注意:维基百科有一篇关于复制省略
相关文章