私人拷贝构造函数/赋值运算符和复制初始化 [英] private copy constructor/assignment operator and copy-initialization
问题描述
在以下code,为什么而行2和3未(使用Visual C ++ 2010)则行1编译
in the following code, why does line 1 compiles while line 2 and 3 does not (using visual C++ 2010)
class ABase
{
protected:
ABase() {}
~ABase() {}
private:
ABase( const ABase& );
const ABase& operator=( const ABase& );
};
class A : ABase
{
};
class B
{
public:
B() {}
~B() {}
private:
B( const B& );
const B& operator=( const B& );
};
int main( void )
{
A a = A(); // line 1
A a2( a ); // line 2
B b = B(); // line 3
return 0;
}
(注意是BA的boost ::不可复制的副本)
(note BA is a copy of boost::noncopyable)
编辑:
我的问题是不知道为什么2号线和3不编译(我知道,拷贝构造函数是私有的),但为什么1号线一样。
edit: My problem is not to know why line 2 and 3 does not compile (I know that, the copy constructor is private), but why line 1 does.
推荐答案
编译器是错误在接受第一次使用。即使副本被省略,拷贝构造函数必须能够访问为code是正确的。
The compiler is wrong in accepting the first use. Even if the copy is elided, the copy constructor must be accessible for the code to be correct.
在这个特殊的情况下,有一个在隐式声明的拷贝构造函数 A
:
In this particular case there is an implicitly declared copy constructor in A
:
§12.8/ 4如果类定义不明确声明一个拷贝构造函数,一个是隐式声明的。
§12.8/4 If the class definition does not explicitly declare a copy constructor, one is declared implicitly.
这是隐含定义的:
§12.8/ 7的隐式声明的拷贝构造函数如果用它来从类类型或者从它的类type108派生的类型)的对象的副本初始化它的类类型的对象隐式定义。 [注:拷贝构造函数隐含定义即使实施省略其使用(12.2)。 ]程序是的病态的如果一个拷贝构造函数隐含定义为其类有:
§12.8/7 An implicitly-declared copy constructor is implicitly defined if it is used to initialize an object of its class type from a copy of an object of its class type or of a class type derived from its class type108). [Note: the copy constructor is implicitly defined even if the implementation elided its use (12.2). ] A program is ill-formed if the class for which a copy constructor is implicitly defined has:
- 类类型(或其阵列)与不可访问或不明确的拷贝构造函数非静态数据成员,或
— a nonstatic data member of class type (or array thereof) with an inaccessible or ambiguous copy constructor, or
- 一个基类不可访问或模棱两可的拷贝构造函数
— a base class with an inaccessible or ambiguous copy constructor.
这篇关于私人拷贝构造函数/赋值运算符和复制初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!