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. 认识div(division)在排版中的作用

    在网页制作过程过中,可以把一些独立的逻辑部分划分出来,放在一个<div>标签中,这个<div>标签的作用就相当于一个容器. 语法: <div>…</div&g ...

  2. WPF命令

    WPF的命令是经常使用的,在MVVM中,RelayCommand更是用得非常多,但是命令的本质究竟是什么,有了事件为什么还要命令,命令与事件的区别是什么呢?MVVM里面是如何包装命令的呢?命令为什么能 ...

  3. Java Calendar 计算时间差

    public static void main(String[] args) { Calendar c=Calendar.getInstance(); int y=2016;//年 int M=1;/ ...

  4. 带计时器的做题器(gui

    新学 1 JCheckBox chckbxA = new JCheckBox("a"); JCheckBox的监听器接口ItemListener,响应方法itemStateChan ...

  5. (转载)让ie6也支持max-width,和max-height实现图片等比例缩放

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  6. (转)QT常用快捷键

    F1        查看帮助F2        跳转到函数定义(和Ctrl+鼠标左键一样的效果)Shift+F2    声明和定义之间切换F4        头文件和源文件之间切换Ctrl+1     ...

  7. mybatis中association的column传入多个参数值

    顾名思义,association是联合查询. 在使用association中一定要注意几个问题.文笔不好,白话文描述一下. 1: <association property="fncg ...

  8. 自然语言处理(1)之NLTK与PYTHON

    自然语言处理(1)之NLTK与PYTHON 题记: 由于现在的项目是搜索引擎,所以不由的对自然语言处理产生了好奇,再加上一直以来都想学Python,只是没有机会与时间.碰巧这几天在亚马逊上找书时发现了 ...

  9. 如何让窗口控件半透明(控件在Paint自己时,首先向主窗口询问,获取主窗口上控件所在区域的背景图)

    在网上关于窗口视觉效果,有2个问题被问得最多:第一个是如何让窗口边框有阴影效果?第二个是如何让窗口控件有半透明效果? 对于第一个问题,我们的答案是用双层窗口模拟或是用Layered Window.在X ...

  10. 【转】HashSet的用法

    原文网址:http://blog.csdn.net/aidesudi/article/details/4720201 Java代码 public class TestHashSet { public  ...