简体   繁体   中英

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

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

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.

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.

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

Make the A(int i) constructor explicit and you should not face this error.

Edit: I think i misunderstood the question. I might delete this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM