Почему в auto_ptr есть конструктор копирования шаблона и оператор переопределения?
Почему в auto_ptr есть конструктор копирования шаблона и оператор переопределения?
Стандарт ISO для C++ определяет следующий интерфейс для auto_ptr. (Это скопировано прямо из стандарта 2003 года.)
namespace std {
template <class Y> struct auto_ptr_ref {};
template<class X> class auto_ptr {
public:
typedef X element_type;
// 20.4.5.1 construct/copy/destroy:
explicit auto_ptr(X* p =0) throw();
auto_ptr(auto_ptr&) throw();
template<class Y> auto_ptr(auto_ptr<Y>&) throw();
auto_ptr& operator=(auto_ptr&) throw();
template<class Y> auto_ptr& operator=(auto_ptr<Y>&) throw();
auto_ptr& operator=(auto_ptr_ref<X> r) throw();
~auto_ptr() throw();
// 20.4.5.2 members:
X& operator*() const throw();
X* operator->() const throw();
X* get() const throw();
X* release() throw();
void reset(X* p =0) throw();
// 20.4.5.3 conversions:
auto_ptr(auto_ptr_ref<X>) throw();
template<class Y> operator auto_ptr_ref<Y>() throw();
template<class Y> operator auto_ptr<Y>() throw();
};
почему есть:
template<class Y> auto_ptr(auto_ptr<Y>&) throw();
Я думаю просто auto_ptr(auto_ptr&) throw();
в порядке
1 ответ
Решение
С конструктором копирования шаблона мы можем инициализировать auto_ptr
из Base
тип класса по Derived
один. Без этого auto_ptr<Base>
а также auto_ptr<Derived>
совершенно не связанные типы.
struct Base {};
struct Derived : Base {};
auto_ptr<Derived> d(new Derived);
auto_ptr<Base> b = d;