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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With