当下面的代码中复制构造函数为私有时,为什么会出现错误C2248? [英] Why the error C2248 when the copy constructor is private in the code below?

查看:194
本文介绍了当下面的代码中复制构造函数为私有时,为什么会出现错误C2248?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码在VS2010中发出error C2248: 'A::A' : cannot access private member declared in class 'A',尽管RVO不需要复制构造函数.为了证明这一点,只需将下面的声明A(const A&);公开,即使没有复制构造函数的定义,代码也可以毫无问题地执行.

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

推荐答案

仅由于您的程序并未最终实际调用复制构造函数,并不意味着可以省略它.声明但未定义它只是通过使函数在编译期间(而不是在链接期间)可用来欺骗"编译器,因此,一旦对它的调用被优化,一切都会起作用".但是RVO是对性能的优化,您的程序必须编写成在没有RVO的情况下正确无误.

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.

这篇关于当下面的代码中复制构造函数为私有时,为什么会出现错误C2248?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆