Smart Pointers 智能指针(一)
来源:互联网 发布:linux怎么安装声卡 编辑:程序博客网 时间:2024/04/30 08:02
有时候,我们需要扩展C++来支持一些特性。
听说过智能指针,但是一直不清楚具体的实现和用途。今天书上看到一点。Smart Pointer其实是一个类,模仿built-in pointer的行为,同时提供built-in pointer类型所不支持的一些功能,比如:自动销毁动态创建的对象(类似java的垃圾回收)。
先看一个简单的例子。(《C++ Common Knowledge》)
template <typename T>
class CheckedPtr{
public:
explicit CheckedPtr( T *p ) : p_( p ) {}
~CheckedPtr() { delete p_; }
T *operator ->() { return get(); }
T &operator *() { return *get(); }
private:
T *p_;
T *get() {
if( !p_ )
throw NullCheckedPointer();
return p_;
}
CheckedPtr( const CheckedPtr & );
CheckedPtr &operator =( const CheckedPtr & );
};
看看auto_ptr实现的代码。(《C++标准库》)
namespace std
...{
template<class T>
class auto_ptr
...{
private:
T* ap;
public:
// constructor & destructor
explicit auto_ptr (T* ptr = 0) throw() : ap(ptr)...{}
~auto_ptr() throw()
...{
delete ap;
}
// Copy & assignment
auto_ptr (auto_ptr& rhs) throw() :ap(rhs.release()) ...{}
template<class Y>
auto_ptr (auto_ptr<Y>& rhs) throw() : ap(rhs.release()) ...{ }
auto_ptr& operator= (auto_ptr& rhs) throw()
...{
reset(rhs.release());
return *this;
}
template<class Y>
auto_ptr& operator= (auto_ptr<Y>& rhs) throw()
...{
reset(rhs.release());
return *this;
}
// Dereference
T& operator*() const throw()
...{
return *ap;
}
T* operator->() const throw()
...{
return ap;
}
// Helper functions
// value access
T* get() const throw()
...{
return ap;
}
// release ownership
T* release() throw()
...{
T* tmp(ap);
ap = 0;
return tmp;
}
// reset value
void reset (T* ptr=0) throw()
...{
if (ap != ptr)
...{
delete ap;
ap = ptr;
}
}
// Special conversions
template<class Y>
struct auto_ptr_ref
...{
Y* yp;
auto_ptr_ref (Y* rhs) : yp(rhs) ...{}
};
auto_ptr(auto_ptr_ref<T> rhs) throw() : ap(rhs.yp) ...{ }
auto_ptr& operator= (auto_ptr_ref<T> rhs) throw()
...{
reset(rhs.yp);
return *this;
}
template<class Y>
operator auto_ptr_ref<Y>() throw()
...{
return auto_ptr_ref<Y>(release());
}
template<class Y>
operator auto_ptr<Y>() throw()
...{
return auto_ptr<Y>(release());
}
};
}
参考书籍:《C++ Common Knowledge》,《C++标准库》
- Smart Pointers 智能指针(一)
- Smart Pointers智能指针
- 智能指针(Smart Pointers)
- Smart Pointers - What, Why, Which? 智能指针
- C++11特性 - Smart Pointers 智能指针
- 智能指针(Smart Pointer) [一]
- 智能指针五大黄金法则(Five Golden rules of smart pointers)
- Boost.Interprocess使用手册翻译之十一:所有权的智能指针(Ownership smart pointers)
- 【more effective c++读书笔记】【第5章】技术(4)——Smart Pointers(智能指针)
- Boost.Interprocess使用手册翻译之十一:所有权的智能指针(Ownership smart pointers)
- Smart pointers to boost your code(智能指针)
- 智能指针(smart pointer)
- C++中的智能指针(smart pointer)
- Smart Pointer--智能指针
- 智能指针(smart pointer)
- 智能指针(smart pointer)
- 智能指针(Smart Pointer)
- 智能指针 smart pointer
- div+css - CSS标准中级联的文档
- 将IP Address Control控件内容写入struct in_addr变量
- 应对新《劳动合同法》 万名华为员工自选去留
- C语言实现二进制文件读写
- 生命不可承受之重
- Smart Pointers 智能指针(一)
- ASP.NET 2.0中客户端脚本总结
- 《沁园春·长沙》
- 也许履历表可以这样填
- 李开复:部分80后创业者不可一世 难成领导者
- 安家了
- VC++新建类不见了。怎么办?
- 中兴ZTE
- linux蓝牙驱动代码阅读笔记