Why can this code elide a copy? [duplicate]

江枫思渺然 提交于 2019-12-23 15:58:54

问题


Possible Duplicates:
constructor invocation mechanism
Why is it an error to use an empty set of brackets to call a constructor with no arguments?

Why can this code elide all copies of A?

#include <iostream>

class A
{
public:
  A() {}
  A(const A&) { std::cout << "Copy" << std::endl; }
};

class B
{
public:
  B(const A& a_) : a(a_) {}
private:
  A a;
};

int main()
{
  B b(A());
}

This code apparently makes no copies of A, and outputs nothing under gcc 3.4 at ideone.


回答1:


The problem is not copy elision, but the meaning of the declaration:

B b(A());
// To get it working the way you expect [1]
B b = B(A());
// Or the slightly more obtuse.
B b((A()));

To the compiler is a function declaration. Google / search SO for the most-vexing-parse. More in the C++ FAQ lite including workarounds.


[1]: This is not exactly the same, as this requires an implicit conversion from A to B. If B was defined as:

class B {
  A a;
public:
  explicit B(const A& a_) : a(a_) {}
};

Then this would not be an alternative.




回答2:


B b(A());

You think this declares a variable? No.

It declares a function b whose return type is B and accepts a parameter of type A (*)() .

See this topic:

  • Most vexing parse: why doesn't A a(()); work?

So if you want to declare a variable, put an extra braces around A() as:

B b((A())); //it declares an object



回答3:


Use:

B b((A()));

your line is a function declaration. Unfortunately C allowed function declarations inside functions (which BTW seem pretty useless to me), so for backward compatibility reasons C++ allows this to. You can enforce variable definition with extra parentheses.



来源:https://stackoverflow.com/questions/6690256/why-can-this-code-elide-a-copy

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