简体   繁体   English

当下面的代码中复制构造函数为私有时,为什么会出现错误C2248?

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

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. 此代码产生error C2248: 'A::A' : cannot access private member declared in class 'A'尽管RVO不需要复制构造函数,但error C2248: 'A::A' : cannot access private member declared in class 'A' VS2010中error C2248: 'A::A' : cannot access private member declared in class 'A'error C2248: 'A::A' : cannot access private member declared in class 'A' To prove this, just turn public the declaration A(const A&); 为了证明这一点,只需将声明A(const A&);公开A(const A&); below, and the code will execute without a problem, even without a definition for the copy constructor . 下面的代码,即使没有为copy构造函数定义,代码也将毫无问题地执行。

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

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

};

A f() { return A(); }

int main()
{
    A a;
    a = f();
}

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. 但是RVO是对性能的优化,您的程序必须编写成在没有RVO的情况下正确无误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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