因此,我有以下代码无法在 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/