c++ - 一个 gcc 编译错误(关于复制 c'tors)这看起来很奇怪(至少对我来说)

标签 c++ gcc g++

因此,我有以下代码无法在 OSX 上的 gcc 4.2.1 上编译。我得到的错误是:

testref.cpp: In function ‘int main()’:
testref.cpp:10: error: ‘A::A(const A&)’ is private
testref.cpp:20: error: within this context

这是代码

#include <cstdio>

class A {
public:
    A() { i=0; printf("A ctor\n"); }
    ~A() { printf("A dtor\n"); }

private:
    A(const A& other) { i=other.i; printf("A COPY CTOR\n"); }
    A& operator=(const A& other) { i=other.i; printf("A COPY operator\n"); return *this; }
private:
    int i;
};

void f(const A &aref) {
    printf("dummy\n");
} 

int main() {
    f(A());
    return 0; 
}

在这种情况下不需要这个复制构造函数,因为 f 获得了一个引用(我将其公开以查看它是否被调用,但它没有)。 此外,我已经让 f 按值获取对象,但仍然没有调用复制构造函数和 operator= 。我怀疑这可能与优化有关。 有什么建议么? 谢谢。

最佳答案

您陷入了一个微妙的标准问题。 GCC 是正确的,但错误非常严重:使用 clang 编译相同内容会给出:

test.cpp:20:7: warning: C++98 requires an accessible copy constructor for class
              'A' when binding a reference to a temporary; was private

编辑:我附近没有我的标准拷贝,无法为您提供完整的推理。希望其他人(或 Google)可以。

关于c++ - 一个 gcc 编译错误(关于复制 c'tors)这看起来很奇怪(至少对我来说),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9129024/

相关文章:

c - GCC:输入文件 `../window.ui.o' 的 i386 架构与 i386:x86-64 输出不兼容

c++ boost::filesystem undefined reference to `boost::filesystem3::path::root_name() const'

qt - 如何在 qmake 和 qt5 中包含带有 -isystem(系统头文件)的 Qt 头文件?

c++ - 在使用 MFC 制作工具栏时发现一些错误

c++ - 为特定类创建 ostream 操纵器

c++ - 计算定向运动的算法

c - gcc编译以 ".C"结尾的c文件(大写C)

gcc - 如何设置 ASAN/UBSAN 报告输出

c++ - 使用 Windows 消息检测媒体插入驱动器

c++ - 如何在 ubuntu 14.04 中通过 apt-get 安装以前版本 (4.4.7) 的 gcc/g++?