Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

template copy constructor

Tags:

c++

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

class Foo
{
public:
   Foo() {}

   template <typename T>
   Foo(const T&) {}   
};
like image 616
FrozenHeart Avatar asked Sep 11 '12 16:09

FrozenHeart


2 Answers

The standard explicitly says that a copy constructor is a non-templated constructor that takes a reference to a possibly const-volatile object of the same type. In the code above you have a conversion but not copy constructor (i.e. it will be used for everything but copies, where the implicitly declared constructor will be used).

Does Foo have a copy constructor?

Yes, the implicitly declared/defined 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 members Foo has and whether the implicitly defined copy constructor manages those correctly.

like image 66
David Rodríguez - dribeas Avatar answered Sep 27 '22 19:09

David Rodríguez - dribeas


According to the Standard, a copy-constructor must be one of the following signature:

Foo(Foo &);
Foo(Foo const &);
Foo(Foo volatile &);
Foo(Foo const volatile &);

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

Since the template constructor in your code doesn't match with the form of any of the above, that is not copy-constructor.

like image 22
Nawaz Avatar answered Sep 27 '22 20:09

Nawaz