我有一种情况,即(似乎)添加第二个复制构造函数会导致在构造函数在派生类中继承时不会调用任何一个.当两者都存在时,复制构造函数被模板化构造函数覆盖.
这是一个MWE:
struct A { template <typename... Args> A (Args&&... args) { std::cout << "non-default ctor called\n"; } A (A&) { std::cout << "copy ctor from non-const ref\n"; } }; struct C :public A { using A::A; }; int main() { C c1; C c2(c1); }
运行此代码,我们看到输出
non-default ctor called copy ctor from non-const ref
这是预期的.
但是,如下所示为结构A添加一个额外的构造函数:
A (const A&) { }
以某种方式导致其他复制构造函数不被调用,因此输出变为
non-default ctor called non-default ctor called
在我的用例中,我想将所有构造函数从基类继承到派生类,包括复制构造函数和其他任何东西.但似乎不知何故,当两个拷贝构造函数都存在时,它们不会被继承.这里发生了什么?
从 https://en.cppreference.com/w/cpp/language/using_declaration起If one of the inherited constructors of Base happens to have the signature that matches a copy/move constructor of the Derived, it does not prevent implicit generation of Derived copy/move constructor (which then hides the inherited version, similar to using operator=).
所以
struct C :public A { using A::A; };
是
struct C :public A { using A::A; C(const C&) = default; C(C&&) = default; };
其中C(const C&)=默认值;类似于
C(const C& c) : A(static_cast<const A&>(c)) {}
所以
struct A { template <typename... Args> A (Args&&... args) { std::cout << "non-default ctor called\n"; } A (A&) { std::cout << "copy ctor from non-const ref\n"; } };
选择模板构造函数,但是
struct A { template <typename... Args> A (Args&&... args) { std::cout << "non-default ctor called\n"; } A (const A&) { std::cout << "copy ctor from const ref\n"; } A (A&) { std::cout << "copy ctor from non-const ref\n"; } };
选择A(const A&).
您可以注意到,还有一个缺陷:
The semantics of inheriting constructors were retroactively changed by a defect report against C++11. Previously, an inheriting constructor declaration caused a set of synthesized constructor declarations to be injected into the derived class, which caused redundant argument copies/moves, had problematic interactions with some forms of SFINAE, and in some cases can be unimplementable on major ABIs. Older compilers may still implement the previous semantics.
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/p0136r1.html
有了这个缺点,你的C级就是
struct C :public A { using A::A; template <typename ...Ts> C(Ts&&... ts) : A(std::forward<Ts>(ts)...) {} // Inherited. C(const C&) = default; C(C&&) = default; };
所以你调用C(C& c):A(c){}(在模板替换之后).