Why the error C2248 when the copy constructor is p

2019-08-17 04:38发布

问题:

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();
}

回答1:

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.