Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why copy constructor is called when passing temporary by const reference?

Tags:

I am passing an unnamed temporary object to a function defined with const ref parameter. The copy ctor of the class is private, and I get a compilation error. I don't understand why a copy constructor is called in this situation.

class A {
public:
  A(int i) {}
private:
  A(const A&) {}
};

void f(const A& a)
{
}

int main()
{
  f(A(1)); // <-- error here: 'A::A(const A&)' is private
}

As expected, when I change the main to:

A a(1);
f(a);

it works.

EDIT: the compiler is gcc 4.1.2

like image 210
davka Avatar asked Jan 19 '11 09:01

davka


2 Answers

The expression A(1) is an rvalue 5.2.3 [expr.type.conv].

In initializing a const reference (the function argument) with an expression that is an rvalue the compiler may create a temporary and copy the value of that expression to the temporary and bind that reference to that temporary. 8.5.3 [dcl.init.ref] / 5.

[...] The constructor that would be used to make the copy shall be callable whether or not the copy is actually done.

Note that this behaviour is due to change in the next version of C++. In the new standard a const reference initialized from a class prvalue must be bound directly to the reference object; no temporary is permitted to be created in this case and a copy constructor is not used or required.

like image 76
CB Bailey Avatar answered Oct 15 '22 09:10

CB Bailey


You can find the answer to your question in Copy Constructor Needed with temp object or go directly to http://gcc.gnu.org/bugs/#cxx%5Frvalbind

The C++ Standard says that a temporary object should be created in this context and its contents filled with a copy of the object we are trying to bind to the reference; it also says that the temporary copy can be elided, but the semantic constraints (eg. accessibility) of the copy constructor still have to be checked.

For further information, you can consult the following paragraphs of the C++ standard: [dcl.init.ref]/5, bullet 2, sub-bullet 1, and [class.temporary]/2.

Starting with GCC 4.3.0, GCC no longer gives an error for this case. This change is based on the intent of the C++ language committee. As of 2010-05-28, the final proposed draft of the C++0x standard permits this code without error.

like image 21
etarion Avatar answered Oct 15 '22 09:10

etarion