我知道这种问题已经被问过很多次了,我已经阅读了关于它的不同答案,以及 ISO 标准的某些部分。
但是,对于 C++ 标准所期望的确切行为,我仍然需要一些说明。
假设这样:
class A
{
public:
A( void ) {}
A( const A & a ) {}
};
class B: public A
{
public:
B( void ) {}
B( const B & b ) {}
};
我知道调用B
类的拷贝构造函数不会调用A
类的拷贝构造函数,我们可以使用初始化列出以便正确执行。
我也知道如何使用 using
来继承构造函数。
但是对于不显式提供复制构造函数而基类提供复制构造函数的派生类,标准究竟有什么要求:
class A
{
public:
A( void ) {}
A( const A & a ) {}
};
class B: public A
{};
我一直认为编译器会为类B
隐式定义一个复制构造函数,从而隐藏类A
的复制构造函数,不会被调用。
但是,看起来不是这样,调用了A
拷贝构造函数。
在 OS X 10.10 上使用 Clang 进行编译。
那么这是强制性的,还是可以由实现定义的,这意味着我们不应该依赖这种行为?
在 C++ 标准中,我发现了以下内容,但对我来说显然不是很清楚:
An inheriting constructor for a class is implicitly defined when it is odr-used (3.2) to create an object of its class type (1.8). An implicitly-defined inheriting constructor performs the set of initializations of the class that would be performed by a user-written inline constructor for that class with a mem-initializer-list whose only mem-initializer has a mem-initializer-id that names the base class denoted in the nested-name-specifier of the using-declaration and an expression-list as specified below, and where the compound-statement in its function body is empty (12.6.2).
我真的很想根据标准并考虑到多重继承来对此进行澄清。
最佳答案
来自 http://en.cppreference.com/w/cpp/language/copy_constructor (强调我的):
Implicitly-defined copy constructor
If the implicitly-declared copy constructor is neither deleted nor trivial, it is defined (that is, a function body is generated and compiled) by the compiler if odr-used. For union types, the implicitly-defined copy constructor copies the object representation (as by std::memmove). For non-union class types (class and struct), the constructor performs full member-wise copy of the object's bases and non-static members, in their initialization order, using direct initialization.
因此,编译器生成的复制构造函数似乎将调用基复制构造函数,就像它调用成员的复制构造函数一样。
关于c++ - 隐式复制构造函数和继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27003791/