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 ...
随机推荐
- JavaScript定时器与执行机制
JavaScript动画中是必须使用到定时器的,这里做一个总结. var label = 'someLable'; console.time(label); console.timeEnd(label ...
- PHP 导入数据库 sql 文件
使用PHP 可以导入sql来建立数据库.代码如下: <?php $hostname = 'localhost'; $dbname = 'test'; $username = 'root'; $p ...
- IDEA Maven Mybatis generator 自动生成代码
IDEA Maven Mybatis generator 自动生成代码 一.安装配置maven以及在Idea中配置maven 安装过程步骤可以看上面的博文,里面介绍得很详细. 二.建数据表 DROP ...
- linux centos 7.5 安装mysql5.7
1 下载tar包,这里使用wget从官网下载(注:下载地址随时可能有变动,wget命令默认下载目录为当前所在文件夹) wget https://dev.mysql.com/get/Downloads/ ...
- 前端自动化Gulp工具常用插件
npm init命令初始化当前文件夹后,在当前文件夹新建gulpfile.js文件.当前目录下的所有操作流都在gulpfile.js文件中定义. gulp自动化 gulp-uglify (JS压缩) ...
- 端口扫描工具nmap
nmap 使用介绍 nmap是目前为止最广为使用的国外端口扫描工具之一.我们可以从[url]http://www.insecure.org/[/url]进行下载,可以很容易的安装到Windows和un ...
- mysql存储之int
开始之前给大家出个问题,数据库表test中两个字段 a int(2),b int(3),现在想执行下面的插入语句 ,) 思考是否可以插入? 答案是能插入 再看下面的语句 ,) 思考能不能插入?注意第 ...
- webstorm 连接svn
先下个Slik-Subversion,安装好,在webstorm中setting中搜索Subversion,把上边安装的地址加上\svn.exe配置在Use command line client,然 ...
- RabbitMQ---7、常见参数含义
简介 本节主要讨论队列声明的各个参数 queueDeclare(String queue, boolean durable, boolean exclusive, Map<String, Obj ...
- C# 条码生成类
using System.Collections; using System.Text.RegularExpressions; namespace DotNet.Utilities { public ...