【发布时间】:2012-12-03 15:20:33
【问题描述】:
考虑以下代码:
class A {
A(const A&);
public:
A() {}
};
int main() {
const A &a = A();
}
此代码在 GCC 4.7.2 下编译良好,但在 Visual C++ 2010 上编译失败,并出现以下错误:
test.cc(8) : error C2248: 'A::A' : cannot access private member declared in class 'A'
test.cc(2) : see declaration of 'A::A'
test.cc(1) : see declaration of 'A'
那么在将临时对象绑定到引用时,是否必须要有一个可访问的复制构造函数?
这和我之前的问题有点关系:
Is there a way to disable binding a temporary to a const reference?
【问题讨论】:
-
是的,copy ctor 是私有的,不是有意实现的。
-
你试过
A().<something>它可能需要复制构造函数从函数内部复制到返回值。 -
Visual C++ 2012 接受代码。
-
是的,可能是编译器优化的问题
-
被测试的编译器的版本号是应该包含在问题中的重要信息。无论如何,这看起来像是一个已修复的错误。如果可以的话,建议您升级到 Visual C++ 2012。 Visual C++ 2012 版本中修复了许多错误。
标签: c++ reference copy-constructor temporary