将临时对象作为参数传递值 - 是拷贝构造函数吗? [英] Passing temporary object as parameter by value - is copy constructor called?

查看:211
本文介绍了将临时对象作为参数传递值 - 是拷贝构造函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果有标准和复制构造函数的类

If a have a class with both standard and copy constructors

class Ex{
       //constructor definitions
}

和一个以参数为参数的函数

and a function that takes it as an argument (by value)

void F(Ex _exin){...}

采取以下代码:

Ex A;
F(A);   //F's parameter is copy constructed from A
F(Ex());  //F's parameter uses the default constructor

在第三行我传递给 F 使用默认构造函数创建 类的新(临时)对象。我的问题是:在创建这个新对象之后,它是否也被复制构造/分配(像第二行中发生的那样),或者是直接在内部中创建?

In the third line I'm passing to F a new (temporary) object of the Ex class using the default constructor. My question is: after this new object is created is it also copy constructed/assigned (like it happens in the second line) or is it directly created "inside" F?

推荐答案

很难找到,但老实说它是在欺骗我。

It was hard to find, but honestly it was bugging me. This is called copy constructor elision.

标准说明了这个例子:

class X{
public:
   X(int);
   X(const X&);
   ~X()
};

X f(X);

void g()
{
   X a(1);
   X b = f(X(2)); //identical to what you have:
   a = f(a);
}

并说明:


12.2 / 2临时对象

12.2/2 Temporary objects

这里,一个实现可能使用临时对象来构造
X然后使用X的复制构造函数传递给f();
或者,可以在用于保存
参数的空间中构造X(2)。 /.../

Here, an implementation might use a temporary in which to construct X(2) before passing it to f() using X's copy-constructor; alternatively, X(2) might be constructed in the space used to hold the argument. /.../

之后,标准解释了返回值优化,这基本上是一样的。

After this the standard explains return value optimization, which is basically the same thing.

所以它实际上与观察到的行为无关,它是由编译器。

So it actually has nothing to do with observed behavior, it is up to the compiler.

这篇关于将临时对象作为参数传递值 - 是拷贝构造函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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