What's auto_ptr?

  The auto_ptr type is provided by the C++ standard library as a kind of a smart pointer that helps to avoid resource leaks when exceptions are thrown. Note that I wrote "a kind of a smart pointer." There are several useful smart pointer types. This class is smart with respect to only one certain kind of problem. For other kinds of problems, type auto_ptr does not help. So, be careful and read the following subsections.

Why need auto_ptr?

  C++中没有垃圾回收机制,需要程序员动态new和delete,这是不方便并且容易出现内存泄露等等问题的。例如:

  This function is a source of trouble. One obvious problem is that the deletion of the object might be forgotten (especially if you have return statements inside the function). There also is a not-so-obvious danger that an exception might occur. Such an exception would exit the function immediately without calling the delete statement at the end of the function. The result would be a memory leak or, more generally, a resource leak.

  An auto_ptr is a pointer that serves as owner of the object to which it refers (if any).

  这有点类似于Qt的内存处理机制,在Qt中,凡是继承于QObject的类,如果给类的对象指定父类,那么该对象会随着父类的destroyed而destroyed。

  As a result, an object gets destroyed automatically when its auto_ptr gets destroyed. A requirement of an auto_ptr is that its object has only one owner.

How to use auto_ptr?

//header file for auto_ptr
#include <memory> void f()
{
//create and initialize an auto_ptr
std::auto_ptr<ClassA> ptr(new ClassA); ... //perform some operations
}

  when we use auto_ptr, there is no need for delete statement any more.

  An auto_ptr has much the same interface as an ordinary pointer; that is, operator * dereferences the object to which it points, whereas operator -> provides access to a member if the object is a class or a structure.

  However, any pointer arithmetic (such as ++) is not defined (this might be an advantage, because pointer arithmetic is a source of trouble).

  注意:不能使用赋值语句将一个普通指针赋给智能指针auto_ptr<>进行初始化。

 

std::auto_ptr<ClassA> ptr1(new ClassA); //OK
std::auto_ptr<ClassA> ptr2 = new ClassA; //ERROR

  赋予auto_ptr一个新值的方法,新值的类型必须是auto_ptr,而不能是任何普通的指针。

std::auto_ptr<ClassA> ptr;                         //create an auto_ptr
ptr = new ClassA; //ERROR
ptr = std::auto_ptr<ClassA>(new ClassA); //OK, delete old object
// and own new

Transfer of Ownership by auto_ptr

  不要使两个智能指针auto_ptr同时指向同一个对象,这样,该对象会被释放两次,从而产生问题!

  Consider, for example, the following use of the copy constructor:

//initialize an auto_ptr with a new object
std::auto_ptr<ClassA> ptr1(new ClassA);//one //copy the auto_ptr
//- transfers ownership from ptr1 to ptr2
std::auto_ptr<ClassA> ptr2(ptr1); //second

  After the first statement, ptr1 owns the object that was created with the new operator. The second statement transfers ownership from ptr1 to ptr2. So after the second statement, ptr2 owns the object created with new, and ptr1 no longer owns the object. The object created by new ClassA gets deleted exactly once — when ptr2 gets destroyed.

  If ptr2 owned an object before an assignment, delete is called for that object:

//initialize an auto_ptr with a new object
std::auto_ptr<ClassA> ptr1(new ClassA);
//initialize another auto_ptr with a new object
std::auto_ptr<ClassA> ptr2(new ClassA);//own one object already ptr2 = ptr1; //assign the auto_ptr
//- delete object owned by ptr2
//- transfers ownership from ptr1 to ptr2

Source and Sink
所有权的传递暗示着auto_ptr的另外一个用途:函数可以使用auto_ptr来将所有权传递到另一个函数中去。
有两种方式可以发生这种情况!
1.A function can behave as a sink of data. This happens if an auto_ptr is passed as an argument to the function by value(传值). In this case, the parameter of the called function gets ownership of the auto_ptr. Thus, if the function does not transfer it again, the object gets deleted on function exit:
  1. void sink(std::auto_ptr<ClassA>); //sink() gets ownership pass by value.
  2. A function can behave as a source of data. When an auto_ptr is returned, ownership of the returned value gets transferred to the calling function. The following example shows this technique:

std::auto_ptr<ClassA> f()
{
std:: auto_ptr<ClassA> ptr(new ClassA); //ptr owns the new object
...
return ptr; //transfer ownership to calling function
} void g()
{
std::auto_ptr<ClassA> p;
for (int i=; i<; ++i) {
p = f(); //p gets ownership of the returned object
//(previously returned object of f() gets deleted)
...
}
} //last-owned object of p gets deleted

以下情况不要使用auto_ptr

auto_ptr总是包含所有权,因此,在参数表或作为返回值中,如果你不想传递所有权,就不要使用auto_ptr。
如果不恰当地使用auto_ptr,会造成极大的错误,如下例子:
//this is a bad example
template <class T>
void bad_print(std::auto_ptr<T> p) //p gets ownership of passed argument
{
//does p own an object ?
if (p.get() == NULL) {
std::cout << "NULL";
}
else {
std::cout << *p;
}
} //Oops, exiting deletes the object to which p refers
std::auto_ptr<int> p(new int);
*p = ; //change value to which p refers
bad_print (p); //Oops, deletes the memory to which p refers
*p = ; //RUNTIME ERROR

  上面这个例子的意图很简单,就是打印输出参数auto_ptr<T> p的值,但是如果是以pass by value的方式调用函数,那么该函数达到意图的同时,也销毁了p指向的对象,这是极其错误的。因此,我们在使用auto_ptr的时候必须非常谨慎!

  既然以传值(pass by value)的方式不行,那么我们是否可以以传引用(pass by reference)的形式调用函数呢?

  You might think about passing auto_ptrs by reference instead. However, passing auto_ptrs by reference confuses the concept of ownership. A function that gets an auto_ptr by reference might or might not transfer ownership. Allowing an auto_ptr to pass by reference is very bad design and you should always avoid it.

  According to the concept of auto_ptrs, it is possible to transfer ownership into a function by using a constant reference. This is very dangerous because people usually expect that an object won't get modified when you pass it as a constant reference. Fortunately, there was a late design decision that made auto_ptrs less dangerous. By some tricky implementation techniques, transfer of ownership is not possible with constant references. In fact, you can't change the ownership of any constant auto_ptr:

const std::auto_ptr<int> p(new int);
*p = ; //change value to which p refers
bad_print(p); //COMPILE-TIME ERROR
*p = ; //OK

auto_ptrs as Members

  在一个自定义类中使用auto_ptr作为类的成员可以防止资源泄露。如果你使用一个auto_ptr智能指针而不是一个普通指针,那么,你不在需要在类析构函数中delete 该成员。
  除此之外,auto_ptr还有一个很大的作用:一般而言,如果在类的构造函数中抛出异常,便有可能出现资源泄露的可能,
class ClassB {
private:
const std::auto_ptr<ClassA> ptr1; //auto_ptr members
const std::auto_ptr<ClassA> ptr2;
public:
//constructor that initializes the auto_ptrs
//- no resource leak possible
ClassB (ClassA val1, ClassA val2)
: ptr1 (new ClassA(val1)), ptr2(new ClassA(val2)) {
} //copy constructor
//- no resource leak possible
ClassB (const ClassB& x)
: ptr1(new ClassA(*x.ptr1), ptr2(new ClassA(*x.ptr2)) {
} //assignment operator
const ClassB& operator= (const ClassB& x) {
*ptr1 = *x.ptr1;
*ptr2 = *x.ptr2;
return *this;
} //no destructor necessary
//(default destructor lets ptr1 and ptr2 delete their objects)
...
};

 对auto_ptr的误用

  1. auto_ptrs cannot share ownership.

  2. auto_ptrs are not provided for arrays.

  3. auto_ptrs are not "universal smart pointers."

  4. auto_ptrs don't meet the requirements for container elements.

一些例子
#include <iostream>
#include <memory>
using namespace std; /* define output operator for auto_ptr
* - print object value or NULL
*/
template <class T>
ostream& operator<< (ostream& strm, const auto_ptr<T>& p)
{
//does p own an object ?
if (p.get() == NULL) {
strm << "NULL"; //NO: print NULL
}
else {
strm << *p; //YES: print the object
}
return strm;
} int main()
{
auto_ptr<int> p(new int());
auto_ptr<int> q; cout << "after initialization:" << endl;
cout << " p: " << p << endl;
cout << " q: " << q << endl; q = p;
cout << "after assigning auto pointers:" << endl;
cout << " p: " << p << endl;
cout << " q: " << q << endl; *q += ; //change value of the object q owns
p = q;
cout << "after change and reassignment:" << endl;
cout << " p: " << p << endl;
cout << " q: " << q << endl;
}

 

STL之auto_ptr的更多相关文章

  1. stl中auto_ptr,unique_ptr,shared_ptr,weak_ptr四种智能指针使用总结

    stl中auto_ptr,unique_ptr,shared_ptr,weak_ptr四种智能指针使用总结 1. auto_ptrauto_ptr主要是用来解决资源自动释放的问题,比如如下代码:voi ...

  2. 【STL】-auto_ptr的用法

    初始化: #include<memory> //auto_ptr header void f() { auto_ptr<classA> ptr(new classA); } 拷 ...

  3. Linux 内核里的“智能指针”【转】

    转自:http://blog.jobbole.com/88279/ 众所周知,C/C++语言本身并不支持垃圾回收机制,虽然语言本身具有极高的灵活性,但是当遇到大型的项目时,繁琐的内存管理往往让人痛苦异 ...

  4. 九章算法:BAT国内班 - 课程大纲

    第1章 国内笔试面试风格及准备方法 --- 分享面试经验,通过例题分析国内面试的风格及准备方法 · 1) C/C++部分: 实现 memcpy 函数 STL 中 vector 的实现原理 · 2)概率 ...

  5. c++11新特性总结(转)

    1.类型与变量相关 1.1.nullptr: 取代了NULL,专用于空指针 1.2.constexpr: 近似const, 可以修饰变量,也可以修饰函数, 修饰变量如: const int globa ...

  6. c++11新特性总结(转。加上重点)

    1.类型与变量相关 1.1.nullptr: 取代了NULL,专用于空指针 1.2.constexpr: 近似const, 可以修饰变量,也可以修饰函数, 修饰变量如: const int globa ...

  7. (转)Delphi2009初体验 - 语言篇 - 智能指针(Smart Pointer)的实现

     转载:http://www.cnblogs.com/felixYeou/archive/2008/08/27/1277250.html 快速导航 一. 回顾历史二. 智能指针简介三. Delphi中 ...

  8. 智能指针(一):STL auto_ptr实现原理

    智能指针实际上是一个类(class),里面封装了一个指针.它的用处是啥呢? 指针与内存 说到指针自然涉及到内存.我们如果是在堆栈(stack)中分配了内存,用完后由系统去负责释放.如果是自定义类型,就 ...

  9. 容器使用的12条军规——《Effective+STL中文版》试读

    容器使用的12条军规——<Effective+STL中文版>试读     还 记的自己早年在学校学习c++的时候,老师根本就没有讲STL,导致了自己后来跟人说 起会C++的时候总是被鄙视, ...

随机推荐

  1. <body>标签,网页上显示的内容放在这里

    在网页上要展示出来的页面内容一定要放在body标签中.如下图是一个新闻文章的网页. 在浏览器中的显示效果: 示例: <!DOCTYPE HTML> <html> <hea ...

  2. 05DotNet基本常用类库

    1.String成员方法(常用) bool Contains(String str);判断字符串对象是否包含给定的字符串; bool StartsWith(String str);判断字符串对象是否以 ...

  3. 关于USACO Training

    做了这么久的题目,突然发现最经典的 USACO Training 还没有做过?加速水一遍吧!我会把题解放在上面的.

  4. Qt中widget重新setParent需要注意的问题

    有时候需要在widget中重新setParent,但会发现setParent有时候会出现问题,比如子窗口不在刷出来等等. 其实,有一点是需要注意的,就是Qt文档里说的,如果你当前widget重新设置了 ...

  5. 【转载】ASP.NET页面运行机制以及请求处理流程

    本文转至 ASP.NET页面运行机制以及请求处理流程 IIS处理页面的运行机制 IIS自身是不能处理像ASPX扩展名这样的页面,只能直接请求像HTML这样的静态文件,之所以能处理ASPX这样扩展名的页 ...

  6. jQuery中自定义简单动画的实现

    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/stri ...

  7. CentOS安装rar、unrar解压缩软件的方法

    闲话不说,centos上如何安装rar.unrar在线解压缩软件呢?如果您的centos是32位的,执行如下命令: wget http://www.rarsoft.com/rar/rarlinux-3 ...

  8. [Python笔记]第十一篇:面向对象

    以上就是本节对于面向对象初级知识的介绍,总结如下: 面向对象是一种编程方式,此编程方式的实现是基于对 类 和 对象 的使用 类 是一个模板,模板中包装了多个“函数”供使用 对象,根据模板创建的实例(即 ...

  9. 使用Intellij IDEA构建spark开发环境

    近期开始研究学习spark,开发环境有多种,由于习惯使用STS的maven项目,但是按照许多资料的方法尝试以后并没有成功,也可能是我环境问题:也可以是用scala中自带的eclipse,但是不太习惯, ...

  10. 关于 wait_event_interruptible() 和 wake_up()的使用

    来源:http://blog.csdn.net/allen6268198/article/details/8112551 1. 关于 wait_event_interruptible() 和 wake ...