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

C++ 为什么C++;auto_ptr有两个复制构造函数和两个赋值运算符,但有一个默认构造函数?,c++,stl,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

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

    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()
explicit auto_ptr(T*ptr=0)throw()
自动旋转(自动旋转和右旋转)投掷()
模板
自动旋转(自动旋转和右旋转)投掷()
auto_ptr&operator=(auto_ptr&rhs)throw()
模板
auto_ptr&operator=(auto_ptr&rhs)throw()

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


分配操作也是如此。我认为。

非模板版本的原因是允许分配/构造相同类型的
auto\u ptr
s。模板化版本允许从相关但不完全相同的指针类型进行构造/分配

auto_ptr <Foo> f = new Foo(); // uses raw pointer constructor
auto_ptr <Foo> f2 = f;  // uses non-templated constructor
auto_ptr <const Foo> f3 = f2; // uses templated constructor   

auto_ptr <Foo> f4 = new foo();
f2 = f4; // uses non-templated assignment operator
f3 = f2; // uses templated assignment operator
auto_ptr f=new Foo();//使用原始指针构造函数
自动_ptr f2=f;//使用非模板构造函数
自动_ptr f3=f2;//使用模板化构造函数
auto_ptr f4=新的foo();
f2=f4;//使用非模板赋值运算符
f3=f2;//使用模板化赋值运算符

它有一个复制构造函数-非模板构造函数

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

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; // *
class A{}
B类:公共A{}
B*B=新的B();
A*A=b;//好啊
自动ptr b(新b);
自动测试a=b;//*
没有模板版本,(*)将无法工作,因为编译器将
auto_ptr
视为与
auto_ptr
完全不同的类型

<>为什么C++ AutoPTPR有两个复制构造函数和两个赋值操作符,但有一个默认构造函数?< /P> 事实并非如此

它有1个默认构造函数(接受0个参数的构造函数)

它有1个复制构造函数(从相同类型的对象复制的构造函数)

它有1个赋值运算符,用于指定相同类型的对象

auto_ptr& operator= (auto_ptr& rhs) throw()
它有一个奇特的模板构造函数,它接受其他类型的auto_ptr(这不是一个复制构造函数,它只是一个普通的构造函数(尽管它是模板化的))

模板
自动旋转(自动旋转和右旋转)投掷()
它有另一个赋值运算符,它接受不同类型的自动指针(因此,是的,这是另一个赋值运算符,但它不是复制赋值运算符(而是转换赋值运算符),因为rhs有不同的类型)

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

Inheritation是使用模板的一个更好的示例,但它也适用于cv差异。@Fred,是的,继承是更常见的情况,但它的示例不那么简洁。看起来f4声明行中丢失了两个内容,您是指auto_ptr f4=new Foo()?不,是静态强制转换(例如,这将允许A*到B*转换)未使用。使用隐式转换。
auto_ptr (auto_ptr& rhs) throw() 
auto_ptr& operator= (auto_ptr& rhs) throw()
template<class Y>
auto_ptr (auto_ptr<Y>& rhs) throw() 
template<class Y>
auto_ptr& operator= (auto_ptr<Y>& rhs) throw()