Why the error C2248 when the copy constructor is private in the code below?

时间秒杀一切 提交于 2019-12-25 03:32:59

问题


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.



来源:https://stackoverflow.com/questions/15972478/why-the-error-c2248-when-the-copy-constructor-is-private-in-the-code-below

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!