Template instance constructor

Given the following code, does Foo have a copy constructor? Is it safe to use Foo with STL containers?

class Foo { public: Foo() {} template <typename T> Foo(const T&) {} }; 
+8
c ++
source share
3 answers

The standard explicitly states that the copy constructor is a non-template constructor that references a possibly const-volatile object of the same type. In the above code, you have a transform, but not a copy constructor (i.e., it will be used for everything except for copies where an implicitly declared constructor will be used).

Does Foo a copy constructor?

Yes, an implicitly declared / specific copy constructor.

Is it safe to use Foo with standard library containers?

With the current definition of Foo it is, but in the general case it depends on what the members of Foo have and whether the implicitly defined copy constructor correctly controls it.

+10
source share

In accordance with the standard, the copy constructor must be one of the following signatures:

 Foo(Foo &); Foo(Foo const &); Foo(Foo volatile &); Foo(Foo const volatile &); Foo(Foo&, int = 0, ); Foo(Foo&, int = 0, float = 1.0); //ie the rest (after first) of the //parameter(s) must have default values! 

Since the template constructor in your code does not match the form of any of the above, this is not a copy constructor.

+4
source share

Foo has a compiler-created copy constructor that cannot be replaced by the template conversion constructor you provided.

 Foo f0; Foo f1(f0); // calls compiler-synthesized copy constructor Foo f2(42); // calls template conversion constructor with T=int 
+1
source share

All Articles