为什么不是复制构造函数调用 [英] why isn't the copy constructor called

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

问题描述


可能重复:

什么是复制精确度和返回值优化?

我很难理解为什么在下面的代码段中,不会调用复制构造函数。

I am having difficulty understanding why in the following piece of code the copy constructor is not called.

#include <iostream>

class Test
{
public:
  Test(int){std::cout << "Test()" << std::endl;}
  Test(const Test&){std::cout << "Test(const Test&)" << std::endl;}
};

int main()
{
  // Test test;
  Test test2(Test(3));

  return 0;
}

有人可以解释为什么只调用构造函数而没有复制构造函数? >
谢谢。

Can someone explain why only the constructor is called and no copy constructor ?
Thanks.

推荐答案

这称为复制elision

编译器允许执行此优化。虽然标准不能保证这一点,任何商业编译器都会在可能的情况下执行此优化。

This is called as copy elision.
The compilers are allowed to do this optimization. Though it is not guaranteed by the standard any commercial compiler will perform this optimization whenever it can.

C ++ 03 12.8.15


[...]在下面的
情况下(可以结合
删除多个副本),允许复制操作的

[...] This elision of copy operations is permitted in the following circumstances (which may be combined to eliminate multiple copies):

[...]


  • 被绑定到一个引用(12.2)
    将被复制到一个类对象与
    相同的cv非限定类型,复制
    操作可以通过
    省略构造临时对象
    直接进入
    省略副本的目标






您可以使用一些编译器设置来禁用此优化,例如gcc的情况,从 手册页


You might use some compiler settings to disable this optimization, like in case of gcc, from the man page:

-fno-elide-constructor




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.

使您的代码在不同的编译器之间不可移植。

However, using this makes your code non portable across different compilers.

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

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