Passing temporary object as parameter by value - is copy constructor called?

两盒软妹~` 提交于 2019-12-18 05:53:12

问题


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

take the following piece of code:

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

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?


回答1:


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

The standard illustrates this example:

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);
}

And it states:

12.2/2 Temporary objects

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.




回答2:


it should call the constructor and the copy-constructor

optimizers could delete unnecessary copying



来源:https://stackoverflow.com/questions/8451212/passing-temporary-object-as-parameter-by-value-is-copy-constructor-called

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!