为什么C++ auto_ptr有两个复制构造函数和两个赋值运算符但只有一个默认构造函数?

Per*_*rge 7 c++ stl

为什么需要两种形式?谢谢

    explicit auto_ptr (T* ptr = 0) throw() 

    auto_ptr (auto_ptr& rhs) throw() 

    template<class Y>
    auto_ptr (auto_ptr<Y>& rhs) throw() 

    auto_ptr& operator= (auto_ptr& rhs) throw()

    template<class Y>
    auto_ptr& operator= (auto_ptr<Y>& rhs) throw()
Run Code Online (Sandbox Code Playgroud)

pet*_*hen 7

它有一个拷贝构造函数 - 非模板化的构造函数.

模板构造函数和赋值运算符允许指定隐式存在的指针类型:

class A {}
class B : public A {}

B * b = new B();
A * a = b;       // OK!


auto_ptr<B> b(new B);
auto_ptr<A> a = b; // *
Run Code Online (Sandbox Code Playgroud)

没有模板版本,(*)将无法工作,因为编译器将其auto_ptr<A>视为完全不同的类型auto_ptr<B>.


Edw*_*nge 6

因为复制构造函数不能是模板.如果他们只有模板版本,那么编译器会生成一个无法正常工作的版本.

对于任务而言......我认为.