auto_ptr与shared_ptr ZZ
http://blog.csdn.net/rogeryi/article/details/1442700
下面的代码来自于VC++ 8.0里面的源码:
下面的例程来自Exceptional C++,Item 37:
// Example 2: Using an auto_ptr
//
void g()
{
T* pt1 = new T;
// right now, we own the allocated object
// pass ownership to an auto_ptr
auto_ptr<T> pt2( pt1 );
// use the auto_ptr the same way
// we'd use a simple pointer
*pt2 = 12; // same as "*pt1 = 12;"
pt2->SomeFunc(); // same as "pt1->SomeFunc();"
// use get() to see the pointer value
assert( pt1 == pt2.get() );
// use release() to take back ownership
T* pt3 = pt2.release();
// delete the object ourselves, since now
// no auto_ptr owns it any more
delete pt3;
} // pt2 doesn't own any pointer, and so won't
// try to delete it... OK, no double delete

// Example 3: Using reset()
//
void h()
{
auto_ptr<T> pt( new T(1) );
pt.reset( new T(2) );
// deletes the first T that was
// allocated with "new T(1)"
} // finally, pt goes out of scope and
// the second T is also deletedauto_ptr对象被销毁的时候,它也会自动销毁自己拥有所有权的对象(嗯,标准的RAAI做法),release可以用来手动放弃所有权,reset
可用于手动销毁内部对象。
auto_ptr(auto_ptr<_Ty>& _Right) _THROW0()
: _Myptr(_Right.release())
{ // construct by assuming pointer from _Right auto_ptr
}
template<class _Other>
auto_ptr<_Ty>& operator=(auto_ptr<_Other>& _Right) _THROW0()
{ // assign compatible _Right (assume pointer)
reset(_Right.release());
return (*this);
}auto_ptr独占了动态对象的所有权。也就是说被拷贝对象在拷贝过程中会被修改,拷贝物与被拷贝物之间是非等价的。这意味着如下的代码是错误的(例程
来自 Exceptional C++ Item 37):
// Example 6: Never try to do work through
// a non-owning auto_ptr
//
void f()
{
auto_ptr<T> pt1( new T );
auto_ptr<T> pt2;
pt2 = pt1; // now pt2 owns the pointer, and
// pt1 does not
pt1->DoSomething();
// error: following a null pointer
}限于某个函数内部或者是某个类的内部。也就是说,动态对象的产生,使用和销毁的全过程是处于一个小的受控的范围,而不会在其中加入一些适应未来时态的扩
展。
An important goal of shared_ptr is to provide a standard shared-ownership pointer.
template<class T> class shared_ptr {

public:

typedef T element_type;

shared_ptr(); // never throws
template<class Y> explicit shared_ptr(Y * p);
template<class Y, class D> shared_ptr(Y * p, D d);
~shared_ptr(); // never throws

shared_ptr(shared_ptr const & r); // never throws
template<class Y> shared_ptr(shared_ptr<Y> const & r); // never throws
template<class Y> explicit shared_ptr(weak_ptr<Y> const & r);
template<class Y> explicit shared_ptr(std::auto_ptr<Y> & r);

shared_ptr & operator=(shared_ptr const & r); // never throws 
template<class Y> shared_ptr & operator=(shared_ptr<Y> const & r); // never throws
template<class Y> shared_ptr & operator=(std::auto_ptr<Y> & r);

void reset(); // never throws
template<class Y> void reset(Y * p);
template<class Y, class D> void reset(Y * p, D d);

T & operator*() const; // never throws
T * operator->() const; // never throws
T * get() const; // never throws bool unique() const; // never throws long use_count() const; // never throws operator unspecified-bool-type() const; // never throws void swap(shared_ptr & b); // never throws };
Note:
Boost文档里面的QA说明了为什么不提供release函数

Q. Why doesn't shared_ptr provide a release() function?
A. shared_ptr cannot give away ownership unless it's unique() because the other copy will still destroythe object.
Consider:
shared_ptr<int> a(new int);
shared_ptr<int> b(a); // a.use_count() == b.use_count() == 2
int * p = a.release();

// Who owns p now? b will still call delete on it in its destructor.
Furthermore, the pointer returned by release() would be difficult to deallocate reliably, as the source shared_ptr could have been created with a custom deleter.
shared_ptr对象(即交换所拥有的对象),有一个bool类型转换操作符使得shared_ptr可用于需要的bool类型的语境下,比如我们通
常用if(pointer)来判断某个指针是否为空。
递动态分配对象,有了引用计数机制,我们现在可以安全地将动态分配的对象包裹在shared_ptr里面跨越模块,跨越线程的边界传递。
shared_ptr为我们自动管理对象的生命周期,嗯,C++也可以体会到Java里面使用引用的美妙之处了。
另外,还记得Effective C++里面(或者其它的C++书籍),Scott
Meyer告诉你的:在一个由多个模块组成的系统里面,一个模块不用试图自己去释放另外一个模块分配的资源,而应该遵循谁分配谁释放的原则。正确的原则但
是有时难免有时让人忽略(过于繁琐),将资源包装在shared_ptr里面传递,而shared_ptr保证了在资源不再被拥有的时候,产生资源的模块
的delete语句会被调用。
class Base
{
}
class Derived : public Base
{
}

shared_ptr<Base> sp_base(new Derived);
Derived* pd = new Derived;
shared_ptr<Derived> sp_derived(pd);
shared_ptr<Base> sp_base2(sp_derived);
A* pa = new A;
xxx_ptr<A> ptr_a_1(pa);
xxx_ptr<A> ptr_a_2(pa);
void DoSomething(xxx_ptr<A>)
{
//do something
}
class A
{
doSomething()
{
xxx_ptr<A> ptr_a(this);
DoSomething(ptr_a);
}
};
int main()
{
A a;
a.doSomething();
//continue do something with a, but it was already destory
}在属于类型A的接口的一部分的非成员函数或者跟A有紧密联系的辅助函数里面使用xxx_ptr<A>作为函数的参数类型。
auto_ptr与shared_ptr ZZ的更多相关文章
- 初次窥见智能指针auto_ptr和shared_ptr
#include <memory>//shared_ptr要用的头文件 using namespace std; class A //测试auto_ptr和shared_ptr的delet ...
- stl中auto_ptr,unique_ptr,shared_ptr,weak_ptr四种智能指针使用总结
stl中auto_ptr,unique_ptr,shared_ptr,weak_ptr四种智能指针使用总结 1. auto_ptrauto_ptr主要是用来解决资源自动释放的问题,比如如下代码:voi ...
- auto_ptr, unique_ptr, shared_ptr and weak_ptr智能指针讲解
笔者介绍:姜雪伟,IT公司技术合伙人,IT高级讲师,CSDN社区专家,特邀编辑,畅销书作者,已出版书籍:<手把手教你架构3D游戏引擎>电子工业出版社和<Unity3D实战核心技术详解 ...
- auto_ptr和shared_ptr
<Effective C++>在资源管理一节提到了智能指针,智能指针中最著名的当属auto_ptr和shared_ptr.本文主要研究两者的实现. auto_ptr的实现: templat ...
- C++ 之 auto_ptr and shared_ptr
1.auto_ptr 这个所谓的只能指针有点鸡肋! 没有引用计数,而且还有一个所有权转移的情况! 当所有权转移后,以前的auto_ptr将会成为null 2.shared_ptr 增加了引用计数,没 ...
- C++ 智能指针 auto_ptr 和 shared_ptr
首先,如果你不知道什么是智能指针,请先移步:C++智能指针简单剖析 1.auto_ptr #ifndef AUTO_PTR_H #define AUTO_PTR_H template<typen ...
- C++智能指针 auto_ptr、shared_ptr、weak_ptr和unique_ptr
手写代码是理解C++的最好办法,以几个例子说明C++四个智能指针的用法,转载请注明出处. 一.auto_ptr auto_ptr这是C++98标准下的智能指针,现在常常已经被C++标准的其他智能指针取 ...
- 关于std:auto_ptr std:shared_ptr std:unique_ptr
很多人听说过标准auto_ptr智能指针机制,但并不是每个人都天天使用它.这真是个遗憾,因为auto_ptr优雅地解决了C++设计和编码中常见的问题,正确地使用它可以生成健壮的代码.本文阐述了如何正确 ...
- <memory>(包括了auto_ptr,shared_ptr等各种指针)
Memory elements This header defines general utilities to manage dynamic memory: Allocators allocator ...
随机推荐
- [DPF] DPF 常见的问题
问题一: SQL6031N Error in the db2nodes.cfg file at line number "5". Reason code "12&qu ...
- 【Qt开发】QTime类
QTime类为用户提供一系列时间的函数,封装的很全面,几乎满足了各种时间的需求. 常用方法介绍 1.QTime addMSecs(int ms) const 当前时间增加毫秒,ms可为负 2.QTim ...
- graphql pass arg
; ; var xhr = new XMLHttpRequest(); xhr.responseType = 'json'; xhr.open("POST", "http ...
- 多线程编程(三)-CountDownLatch的使用
CountDownLatch的介绍 类CountDownLatch是同步功能得一个辅助类,使用效果就是给定一个计数,当使用CountDownLatch类的线程判断计数不为0时,则呈wait状态,如果是 ...
- 使用VNC访问Windows桌面
1. 背景介绍 两台电脑,一个笔记本,一个台式机 笔记本上装的是Windows 10, 通过上网小助手上网 (P.S. 上网小助手...Stupid Policy...) 台式机上装的是Ubuntu ...
- sqlmap中##和$$的区别
一. 主要区别 #a# //解析sqlmap配置文件时自动加单引号,即'a' $a$ //解析sqlmap配置文件时不加单引号,即a 如果传进来的条件需要order by的话,那一定用第二种 #是把传 ...
- Redis: under the hood---转载
http://pauladamsmith.com/articles/redis-under-the-hood.html#redis-under-the-hood How does the Redis ...
- 常用命令(Linux、Android、adb)
1. Linux 2. Android 1. pm (package Manager) 1). 安装APK(一般不使用,用adb我感觉更好) pm install -r /data/card/Ap ...
- 最近在研究asp.net mvc
看了很多大牛写的博客,依然对mvc云里雾里. 有一点是毋庸置疑的C应该是一座桥梁建立在model和view之间. 在ASP.NET MVC中,控制器通常是继承System.Web.Mvc.Contro ...
- DataGridview 绘制行序号
RowPostpaint 事件 通过Rectangle(矩形的意思)对象绘制矩形区域,然后在通过textRenderer的DeawText方法来绘制序列号. Rectangle(x,y width ...