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
// Example 2: Using an auto_ptr //
// void g()
void g() {
{ T* pt1 = new T;
     T* pt1 = new T; // right now, we own the allocated object
     // right now, we own the allocated object // pass ownership to an auto_ptr
     // pass ownership to an auto_ptr auto_ptr<T> pt2( pt1 );
     auto_ptr<T> pt2( pt1 ); // use the auto_ptr the same way
     // use the auto_ptr the same way // we'd use a simple pointer
     // we'd use a simple pointer *pt2 = 12;       // same as "*pt1 = 12;"
     *pt2 = 12;       // same as "*pt1 = 12;"
 pt2->SomeFunc(); // same as "pt1->SomeFunc();"
     pt2->SomeFunc(); // same as "pt1->SomeFunc();" // use get() to see the pointer value
     // use get() to see the pointer value assert( pt1 == pt2.get() );
     assert( pt1 == pt2.get() ); // use release() to take back ownership
     // use release() to take back ownership T* pt3 = pt2.release();
     T* pt3 = pt2.release(); // delete the object ourselves, since now
     // delete the object ourselves, since now // no auto_ptr owns it any more
     // no auto_ptr owns it any more delete pt3;
     delete pt3;
 } // pt2 doesn't own any pointer, and so won't
} // pt2 doesn't own any pointer, and so won't // try to delete it... OK, no double delete
 // try to delete it... OK, no double delete 
 
 // Example 3: Using reset()
// Example 3: Using reset() //
// void h()
void h() {
{ auto_ptr<T> pt( new T(1) );
     auto_ptr<T> pt( new T(1) ); pt.reset( new T(2) );
     pt.reset( new T(2) ); // deletes the first T that was
    // deletes the first T that was // allocated with "new T(1)"
    // allocated with "new T(1)"
 } // finally, pt goes out of scope and
} // finally, pt goes out of scope and // the second T is also deleted
 // the second T is also deletedauto_ptr对象被销毁的时候,它也会自动销毁自己拥有所有权的对象(嗯,标准的RAAI做法),release可以用来手动放弃所有权,reset
可用于手动销毁内部对象。
 auto_ptr(auto_ptr<_Ty>& _Right) _THROW0()
         auto_ptr(auto_ptr<_Ty>& _Right) _THROW0() : _Myptr(_Right.release())
                 : _Myptr(_Right.release())
 {        // construct by assuming pointer from _Right auto_ptr
                 {        // construct by assuming pointer from _Right auto_ptr }
                 } 
  template<class _Other>
         template<class _Other> auto_ptr<_Ty>& operator=(auto_ptr<_Other>& _Right) _THROW0()
                 auto_ptr<_Ty>& operator=(auto_ptr<_Other>& _Right) _THROW0()
 {        // assign compatible _Right (assume pointer)
                 {        // assign compatible _Right (assume pointer) reset(_Right.release());
                 reset(_Right.release()); return (*this);
                 return (*this); }
                 }auto_ptr独占了动态对象的所有权。也就是说被拷贝对象在拷贝过程中会被修改,拷贝物与被拷贝物之间是非等价的。这意味着如下的代码是错误的(例程
来自 Exceptional C++ Item 37):
 // Example 6: Never try to do work through
// Example 6: Never try to do work through
 //            a non-owning auto_ptr
//            a non-owning auto_ptr //
// void f()
void f() {
{ auto_ptr<T> pt1( new T );
     auto_ptr<T> pt1( new T ); auto_ptr<T> pt2;
     auto_ptr<T> pt2;
 pt2 = pt1; // now pt2 owns the pointer, and
     pt2 = pt1; // now pt2 owns the pointer, and
 // pt1 does not
              // pt1 does not pt1->DoSomething();
     pt1->DoSomething();
 // error: following a null pointer
              // 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 {
 template<class T> class shared_ptr { 
 
 public:
    public: 
 
 typedef T element_type;
      typedef T element_type; 
 
 shared_ptr(); // never throws
      shared_ptr(); // never throws
 template<class Y> explicit shared_ptr(Y * p);
      template<class Y> explicit shared_ptr(Y * p);
 template<class Y, class D> shared_ptr(Y * p, D d);
      template<class Y, class D> shared_ptr(Y * p, D d);
 ~shared_ptr(); // never throws
      ~shared_ptr(); // never throws 
 
 shared_ptr(shared_ptr const & r); // 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> 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(weak_ptr<Y> const & r);
 template<class Y> explicit shared_ptr(std::auto_ptr<Y> & r);
      template<class Y> explicit shared_ptr(std::auto_ptr<Y> & r); 
 
 shared_ptr & operator=(shared_ptr const & r); // never throws
      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=(shared_ptr<Y> const & r); // never throws
 template<class Y> shared_ptr & operator=(std::auto_ptr<Y> & r);
      template<class Y> shared_ptr & operator=(std::auto_ptr<Y> & r); 
 
 void reset(); // never throws
      void reset(); // never throws
 template<class Y> void reset(Y * p);
      template<class Y> void reset(Y * p);
 template<class Y, class D> void reset(Y * p, D d);
      template<class Y, class D> void reset(Y * p, D d); 
 
 T & operator*() const; // never throws
      T & operator*() const; // never throws
 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 };
      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:
Note: 
  Boost文档里面的QA说明了为什么不提供release函数
Boost文档里面的QA说明了为什么不提供release函数 
 
 Q. Why doesn't shared_ptr provide a release() function?
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 destroy
A. shared_ptr cannot give away ownership unless it's unique() because the other copy will still destroythe object.
 Consider:
Consider: shared_ptr<int> a(new int);
shared_ptr<int> a(new int);
 shared_ptr<int> b(a); // a.use_count() == b.use_count() == 2
shared_ptr<int> b(a); // a.use_count() == b.use_count() == 2 
  int * p = a.release();
int * p = a.release(); 
 
 // Who owns p now? b will still call delete on it in its destructor.
// 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,
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 Base {
{ }
}
 class Derived : public Base
class Derived : public Base {
{ }
} 
 
 shared_ptr<Base> sp_base(new Derived);
shared_ptr<Base> sp_base(new Derived); Derived* pd = new Derived;
Derived* pd = new Derived; 
  shared_ptr<Derived> sp_derived(pd);
shared_ptr<Derived> sp_derived(pd); shared_ptr<Base> sp_base2(sp_derived);
shared_ptr<Base> sp_base2(sp_derived); A* pa = new A;
A* pa = new A; xxx_ptr<A> ptr_a_1(pa);
xxx_ptr<A> ptr_a_1(pa); xxx_ptr<A> ptr_a_2(pa);
xxx_ptr<A> ptr_a_2(pa); void DoSomething(xxx_ptr<A>)
void DoSomething(xxx_ptr<A>) {
{
 //do something
         //do something }
} 
  class A
class A {
{ doSomething()
         doSomething() {
         {
 xxx_ptr<A> ptr_a(this);
                 xxx_ptr<A> ptr_a(this); DoSomething(ptr_a);
                 DoSomething(ptr_a); }
         } };
}; 
  int main()
int main() {
{
 A a;
         A a; a.doSomething();
         a.doSomething();
 //continue do something with a, but it was already destory
         //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 ... 
随机推荐
- java io流 数据流 DataInputStream、DataOutputStream、ByteArrayInputStream、ByteArrayOutputStream
			例子程序: package io; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import ... 
- memcached 学习笔记 3
			适合什么场合 memcached不是万能的,它也不是适用在所有场合. Memcached是“分布式”的内存对象缓存系统,那么就是说,那些不需要“分布”的,不需要共享的,或者干脆规模小到只有一台服务器的 ... 
- mysql中sql中的注释
			学习mysql好久了,oracle也是,但是经常使用oracle,有一天突然想,oracle的sql语法中有注释,那么mysql中是不是也有注释,于是从网上搜了一下,原来mysql中的注释还真不少,下 ... 
- vlog常用参数解析
			1. -f <filelist> : compile all files in filelist --------------------------------------------- ... 
- 虚拟机安装Ubuntu的上网设置(有线网络和无线网络)
			(恩,是转的) 虚拟机下ubuntu共享方式上网: 一. 有线网络 在有线网络的条件下,vmware的安装非常简单,上网方式几乎不用怎么设置(默认NAT模式) 如果默认情况下不能上网,则按以下 ... 
- shell脚本:行列转换
			Mybatis中写sql,如select,会涉及到一长串列名. `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(100) COLLATE ut ... 
- Python Qt的窗体开发的基本操作
			本文章采用的是Qt4,是python(x,y) 套件中集成的,为啥不集成Qt5呢,懒得装啊:) 正文: 首先看成品: 这个程序的功能是输入原价和降价的百分比,计算出最后的价格. 设计器部分 然后就是开 ... 
- Spring 学习(十)--- Dispatch 分发逻辑
			问题 : Spring 分发逻辑是如何的 概述 本文讲解Spring 请求到返回视图的分发过程. 分发逻辑 分发逻辑可以使用下图来表示. 总共七个步骤 : 接收请求,经过 DispatcherServ ... 
- OpenGL开发入门
			1.OpenGL简介: OpenGL ES (OpenGL for Embedded Systems) 是 OpenGL三维图形 API 的子集,针对手机.PDA和游戏主机等嵌入式设备而设计.该API ... 
- Ubuntu14.04默认cmake升级为3.x
			由于Ubuntu14.04的cmake版本为2.8.x,而如果需要cmake3.x版本时,无法生成makefile,有两种方法可以安装cmake3.4.1: sudo apt-get install ... 
