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 ...
 
随机推荐
- [大数据入门] Cloudera-Hadoop 理论
			
Hadoop 发明者Doug Cutting Cloudera Hadoop 是基于Java 开发的集群环境,所以每个节点都需要安装Java 运行环境(即JDK),通过Cloudera Manager ...
 - struts2上传单个文件
			
项目目录: struts.xml配置: <constant name="struts.enable.DynamicMethodInvocation" value=" ...
 - 关于function构造函数特别注意的
			
function在javascript中是对象,所以function持有构造函数例子:var a = new Function("x","y","re ...
 - iview中使用Tag时进行数据的变化和实现将输入内容转化为标签输出数组
			
上代码 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title ...
 - leetcode4:Permutation
			
#include <utility> #include <iostream> #include <vector> #include <algorithm> ...
 - 【c++】字符串流输出恢复状态问题
			
缘起 #include <iostream> #include <sstream> using namespace std; int main() { istringstrea ...
 - 前端自动化Gulp工具常用插件
			
npm init命令初始化当前文件夹后,在当前文件夹新建gulpfile.js文件.当前目录下的所有操作流都在gulpfile.js文件中定义. gulp自动化 gulp-uglify (JS压缩) ...
 - Rechnernetz
			
1.Der Aufbau des Internets 1.1 Randabschnitt Er besteht aus Rechner,der mit Internet verbunden ist.D ...
 - Linux笔记-Makefile伪指令解析
			
本文是我在博客里面找到的,觉得对makefile的伪指令介绍得非常详细了!也提到了伪指令为何要用.PHONY:来声明!希望我的这篇转过来的文章能够帮助大家理解makefile的伪指令! 我的理解: 拿 ...
 - [转]从客户端中检测到有潜在危险的Request.Form值的详细解决
			
本文转自:http://www.knowsky.com/887593.html asp.net1.1后引入了对提交表单自动检查是否存在XSS(跨站脚本攻击)的能力.当用户试图用之类的输入影响页面返回结 ...