Why does it call the copy constructor when passing a temporary value via a const reference?

I am passing an unnamed temporary object to the function defined with the const ref parameter. The copy instance of the class is private, and I get a compilation error. I do not understand why the 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 main to:

 A a(1); f(a); 

it works.

EDIT: gcc 4.1.2 compiler

+22
c ++ gcc pass-by-reference copy-constructor
Jan 19 2018-11-11T00:
source share
3 answers

You can find the answer to your question in the Copy constructor needed with a temporary object , or go directly to http://gcc.gnu.org/bugs/#cxx%5Frvalbind

The C ++ standard says that a temporary object must be created in this context and its contents, a filled copy of the object that we are trying to bind to the link; he also says that the temporary copy can be canceled, but the semantic restrictions (e.g. accessibility) of the copy constructor still need to be checked.

For more information, you can consult the following C ++ standard items: [dcl.init.ref] / 5, bullet 2, sub-bullet 1 and [Class.temporary] / 2.

Starting with GCC 4.3.0, GCC no longer works giving an error for this case. This change is based on C ++. Starting from 2010-05-28, the final proposed draft C ++ 0x standard resolves this code without errors.

+17
Jan 19 '11 at 9:40
source share

Expression A(1) is rvalue 5.2.3 [expr.type.conv].

When initializing a const reference (function argument) with an expression that is an rvalue, the compiler can create a temporary one and copy the value of this expression into a temporary one and bind this link to this temporary one. 8.5.3 [dcl.init.ref] / 5.

[...] The constructor that will be used to create the copy can be called regardless of whether the copy is actually running.

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

+18
Jan 19 '11 at 9:40
source share

Since (1) calls the constructor A (int i), and then A (const A &) is called in the void f (const A &) call.

Make constructor A (int i) explicit, and you should not encounter this error.

Edit: I think I misunderstood the question. I could remove this.

0
Jan 19 '11 at 9:25 a.m.
source share



All Articles