首页 > 应用开发 > IT综合 > auto_ptr_ref的奇妙(下) (转)
在我们前面谈到的auto_ptr,它的复制操作的参数类型恰好是非常量引用。所以对于下面的情况它就不能正确处理。XML:namespace prefix = o ns = "urn:schemas-microsoft-com:Office:office" />
auto_ptr
auto_ptr
{return auto_ptr
auto_ptr
而这种情况不但合法,也是很常见的,我们不能拒绝这种用法,怎么办?天才的C++库设计者已经为我们想到了这一点,auto_ptr_ref的引入就是为了解决这个问题。仔细观察最下面的auto_ptr实现代码,我们会看到这样几行:
/* special conversions with auxiliary type to enable copies and assignments */
auto_ptr(auto_ptr_ref
: ap(rhs.yp) {
}
auto_ptr& operator= (auto_ptr_ref
reset(rhs.yp);
return *this;
}
template
operator auto_ptr_ref
return auto_ptr_ref
}
这就是关键所在了。对于一个auto_ptr右值,不可能为它调用正常的赋值运算符函数和复制构造函数,举个例子说明,对于语句
auto_ptr
首先生成临时对象右值auto_ptr
template
{ return auto_ptr_ref
由auto_ptr
auto_ptr(auto_ptr_ref
: ap(rhs.yp) {
}
它的参数类型不是引用,采用的是传值(by value),所以可以接受右值,这时候,调用auto_ptr_ref
我们的整个探险过程就结束了。最好参考《The C++ Standard Library》中讲解auto_ptr使用的章节一起阅读。这样auto_ptr的使用和所有设计原理对我们就不再神秘了。
附录:auto_ptr的实现代码,来自Nicolai M. Josuttis
/* class auto_ptr
* - improved standard confoRming implementation
*/
namespace std {
// auxiliary type to enable copies and assignments (now global)
template
struct auto_ptr_ref {
Y* yp;
auto_ptr_ref (Y* rhs)
: yp(rhs) {
}
};
template
class auto_ptr {
private:
T* ap; // refers to the actual owned object (if any)
public:
typedef T element_type;
// constructor
explicit auto_ptr (T* ptr = 0) throw()
: ap(ptr) {
}
// copy constructors (with implicit conversion)
// - note: nonconstant parameter
auto_ptr (auto_ptr& rhs) throw()
: ap(rhs.release()) {
}
template
auto_ptr (auto_ptr
: ap(rhs.release()) {
}
// assignments (with implicit conversion)
// - note: nonconstant parameter
auto_ptr& operator= (auto_ptr& rhs) throw() {
reset(rhs.release());
return *this;
}
template
auto_ptr& operator= (auto_ptr
reset(rhs.release());
return *this;
}
// destructor
~auto_ptr() throw() {
delete ap;
}
// value access
T* get() const throw() {
return ap;
}
T& operator*() const throw() {
return *ap;
}
T* operator->() 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 with auxiliary type to enable copies and assignments
*/
auto_ptr(auto_ptr_ref
: ap(rhs.yp) {
}
auto_ptr& operator= (auto_ptr_ref
reset(rhs.yp);
return *this;
}
template
operator auto_ptr_ref
return auto_ptr_ref
}
template
operator auto_ptr
return auto_ptr
}
};
}
吴桐写于2003.6.16
最近修改2003.6.16
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/10752019/viewspace-959304/ ,如需转载,请注明出处,否则将追究法律责任。