复制构造函数elision? [英] Copy constructor elision?

查看:101
本文介绍了复制构造函数elision?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不太明白为什么在使用VC2010使用调试模式构建时不会调用此复制构造函数。

  class SomeClass 
{
public:
SomeClass(int无意义){}

SomeClass(const SomeClass& sc)
{
cout< ; 复制构造函数调用! << endl;
}
};

int main()
{
SomeClass test(SomeClass(9999)); //复制构造函数未调用。
}



我认为这与RVO无关,因为我没有返回任何值。



更有趣的是,当我使复制构造函数私有时,编译器甚至不会编译,即使它省略了复制构造函数。



提前感谢。

解决方案

这是由编译器完成的优化。根据语言规范,编译器允许省略对复制构造函数的调用。



只有语义检查才需要可访问的副本构造函数,即使它不是实际调用的。



但是,如果你用 -fno-elide-constructors 选项与GCC,则不会执行复制检测,并且将调用复制构造函数。 GCC文档说, / p>


-fno-elide-constructors



C ++标准允许实现省略创建只用于初始化相同类型的另一个对象的临时。 指定此选项会停用该优化,并强制G ++在所有情况下调用复制构造函数。


MSVC10,您可以使用 / Od

:维基百科有一篇关于的文章。 /en.wikipedia.org/wiki/Copy_elisionrel =nofollow noreferrer> copy elision


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. 
}

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.

Thanks in advance.

解决方案

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.

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

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.

With MSVC10, you can use /Od which according to the MSDN turns off all optimizations in the program.

Note : Wikipedia has an article on copy elision

这篇关于复制构造函数elision?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆