Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does C++ auto_ptr have two copy constructors and two assignment operators but one default constructor?

Tags:

c++

stl

Why does it need two forms? Thanks

    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()
like image 280
Percy Flarge Avatar asked Nov 29 '10 19:11

Percy Flarge


1 Answers

It has one copy constructor - the non-templated one.

The template constructor and assignment operator allow assignment of pointer types for which an implicit exists:

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; // *

without the template versions, (*) wouldn't work, as the compiler treats auto_ptr<A> as a completely different type than auto_ptr<B>.

like image 76
peterchen Avatar answered Sep 22 '22 23:09

peterchen