0

This code emits error C2248: 'A::A' : cannot access private member declared in class 'A' in VS2010, although RVO doesn't need a copy constructor. To prove this, just turn public the declaration A(const A&); below, and the code will execute without a problem, even without a definition for the copy constructor .

class A
{
    int i;
    A(const A&);

    public:
    A() : i(1) {}

};

A f() { return A(); }

int main()
{
    A a;
    a = f();
}
Nazik
  • 8,696
  • 27
  • 77
  • 123
Belloc
  • 6,318
  • 3
  • 22
  • 52

1 Answers1

3

Just because your program doesn't end up actually invoking the copy constructor does not mean it is permissible to omit it. Declaring but not defining it just "tricks" the compiler by making the function available during compilation but not during linking, so once the call to it is optimized out, everything "works." But RVO is an optimization for performance, and your program must be written such that it is correct without the presence of RVO.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • But RVO is always applied in MS compilers, even in debug builds. So in this case, the compiler knows that the copy constructor isn't necessary. – Belloc Apr 12 '13 at 13:55
  • I guess a quote from The Standard would be useful here. – sharptooth Apr 12 '13 at 13:59
  • @sharptooth: Do *you* really need it? :) From C++03: 3.2p2 *A copy constructor is used even if the call is actually elided by the implementation.* 12.8p14 *A program is ill-formed if the copy constructor or the copy assignment operator for an object is implicitly used and the special member function is not accessible (clause 11).* – David Rodríguez - dribeas Apr 12 '13 at 14:08
  • @DavidRodríguez-dribeas: Yes, I do - it's often easier to just blame everything on the language. – sharptooth Apr 12 '13 at 14:18
  • @sharptooth: At any rate there you have the relevant quotes. You can probably locate the same text in C++11 somewhere around those sections – David Rodríguez - dribeas Apr 12 '13 at 15:57
  • @sharptooth Have you located the text in C++11? – Belloc Apr 12 '13 at 17:52
  • @user1042389: Nope, I don't have access to the text. – sharptooth Apr 22 '13 at 06:41