8

给定以下代码, Foo 是否具有复制构造函数?将 Foo 与 STL 容器一起使用是否安全?

class Foo
{
public:
   Foo() {}

   template <typename T>
   Foo(const T&) {}   
};
4

3 回答 3

10

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.

于 2012-09-11T16:48:24.090 回答
4

根据标准,复制构造函数必须是以下签名之一:

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!

由于您代码中的模板构造函数与上述任何形式都不匹配,因此不是 复制构造函数。

于 2012-09-11T16:49:51.170 回答
1

Foo has a compiler generated copy constructor, which cannot be replaced by the template conversion constructor you have provided.

Foo f0;
Foo f1(f0); // calls compiler-synthesized copy constructor
Foo f2(42); // calls template conversion constructor with T=int
于 2012-09-11T16:48:24.107 回答