auto_ptr

namespace std{
template <class Y>
struct auto_ptr_ref{};

template <class T>
class auto_ptr{
typedef T element_type;
explicit auto_ptr(T *ptr=0) thow();
auto_ptr(auto_ptr &) thow();
template <class U>
auto_ptr(auto_ptr<U> &) thow();
auto_ptr & operator=(auto_ptr &) thow();
template <class U>
auto_ptr & operator= (auto_ptr<U> &) throw();

~auto_ptr() throw();
T * get() const throw();
T & operator *() const throw();
T * operator->const throw();
T *release() throw();
void reset(T * ptr=0) throw();
public:
auto_ptr(auto_ptr_ref<T>) throw();
auto_ptr & operator=(auto_ptr_ref<T> rhs) throw();
template<class U> operator auto_ptr_ref<U> () throw();
template<class U> opetator auto_ptr<U>() throw();
};       
}
explicit auto_ptr::auto_ptr(T *ptr) throw()
1)生成一个auto_ptr,并拥有ptr所指对象
2)这一操作完成后,*this成为ptr所指对象的唯一拥有者。不容许再有其他拥有者。
c++中的explicit关键字用来修饰类的构造函数,表明该构造函数是显式的,既然有"显式"那么必然就有"隐式",那么什么是显示而什么又是隐式的呢?
如果c++类的构造函数有一个参数,那么在编译的时候就会有一个缺省的转换操作:将该构造函数对应数据类型的数据转换为该类对象,如下面所示:
class MyClass
{
public:
MyClass( int num );
}
....
MyClass obj = 10; //ok,convert int to MyClass
在上面的代码中编译器自动将整型转换为MyClass类对象,实际上等同于下面的操作:
MyClass temp(10);
MyClass obj = temp;
上面的所有的操作即是所谓的"隐式转换"。

如 果要避免这种自动转换的功能,我们该怎么做呢?嘿嘿这就是关键字explicit的作用了,将类的构造函数声明为"显示",也就是在声明构造函数的时候前 面添加上explicit即可,这样就可以防止这种自动的转换操作,如果我们修改上面的MyClass类的构造函数为显示的,那么下面的代码就不能够编译 通过了,如下所示:
class MyClass
{
public:
explicit MyClass( int num );
}
....
MyClass obj = 10; //err,can't non-explict convert

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值