question about copy constructor in auto_ptr

D

dolphin

Hi All
Today , I read the source code of auto_ptr. I have a question
about the copy constructor of auto_ptr.
template<class _Ty>
class auto_ptr
{
..................
}
there is a copy constructor below

template <class _Ty1>
auto_ptr(auto_ptr<_Ty1>& __a) : _M_ptr(__a.release()) {}
What is the template<class _Ty1> mean? What is the different between
the type Ty and type _Ty1? Can a smart pointer of type _Ty1 be
reassigned to a smart pointer of type Ty?
 
B

Barry

dolphin said:
Hi All
Today , I read the source code of auto_ptr. I have a question
about the copy constructor of auto_ptr.
template<class _Ty>
class auto_ptr
{
.................
}
there is a copy constructor below

template <class _Ty1>
auto_ptr(auto_ptr<_Ty1>& __a) : _M_ptr(__a.release()) {}
What is the template<class _Ty1> mean? What is the different between
the type Ty and type _Ty1? Can a smart pointer of type _Ty1 be
reassigned to a smart pointer of type Ty?

IIF _Ty is convertible to _Ty1, say Derived to Base

#include <memory>

struct Base {};
struct Derived : Base {};

int main() {
auto_ptr<Derived> spD(new Derived);
auto_ptr<Base> spB(spD);
}
 
Y

yanlinlin82

Hi All
Today , I read the source code of auto_ptr. I have a question
about the copy constructor of auto_ptr.
template<class _Ty>
class auto_ptr
{
.................}

there is a copy constructor below

template <class _Ty1>
auto_ptr(auto_ptr<_Ty1>& __a) : _M_ptr(__a.release()) {}
What is the template<class _Ty1> mean? What is the different between
the type Ty and type _Ty1? Can a smart pointer of type _Ty1 be
reassigned to a smart pointer of type Ty?

The template<class _Ty1> means another type than auto_ptr<Ty>.
It's not a copy constructor, but a normal constructor with one
parameter.
The auto_ptr<_Ty1> can be reassigned to auto_ptr<_Ty>, only when _Ty1
can be reassigned to _Ty. Such as, when _Ty1 is equal to _Ty, or _Ty1
is the derived class of _Ty.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,228
Members
46,818
Latest member
SapanaCarpetStudio

Latest Threads

Top