mercredi 4 juillet 2018

Surprising behavior in multiple copy constructor inheritance

Starting with C++11, there can be two copy constructors, one taking a parameter of type T&, and one taking a parameter of type const T&.

I have a situation where (seemingly) adding a second copy constructor causes neither one to get called, when the constructors are inherited in a derived class. The copy constructor is overridden by a templatized constructor when both are present.

Here is a 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);
}

Running this code, we see output

non-default ctor called
copy ctor from non-const ref

which is as expected.

However, adding an additional constructor to struct A as follows:

  A (const A&) { }

somehow causes the other copy constructor not to get called, so the output becomes

non-default ctor called
non-default ctor called

In my use case, I want to inherit all the constructors from a base class into a derived class, including the copy constructors and anything else. But it seems that somehow the two copy constructors don't get inherited when they are both present. What is going on here?

Aucun commentaire:

Enregistrer un commentaire