C++编程思想 第2卷 第1章 异常处理 清理 auto_ptr

在C++程序中动态分配内存是频繁使用的资源,使用C++标准提供了一个RAII
封装类,用于封装指向分配的堆内存 heap memory 的指针,这就使得程序
能够自动释放这些内存

//: C01:Auto_ptr.cpp
// From "Thinking in C++, Volume 2", by Bruce Eckel & Chuck Allison.
// (c) 1995-2004 MindView, Inc. All Rights Reserved.
// See source code use permissions stated in the file 'License.txt',
// distributed with the code package available at www.MindView.net.
// Illustrates the RAII nature of auto_ptr.
#include <memory>
#include <iostream>
#include <cstddef>
using namespace std;

class TraceHeap {
  int i;
public:
  static void* operator new(size_t siz) {
    void* p = ::operator new(siz);
    cout << "Allocating TraceHeap object on the heap "
         << "at address " << p << endl;
    return p;
  }
  static void operator delete(void* p) {
    cout << "Deleting TraceHeap object at address "
         << p << endl;
    ::operator delete(p);
  }
  TraceHeap(int i) : i(i) {}
  int getVal() const { return i; }
};

int main() {
  auto_ptr<TraceHeap> pMyObject(new TraceHeap(5));
  cout << pMyObject->getVal() << endl;  // Prints 5
  getchar();
} ///:~

TraceHeap类重载了new 运算符和 delete 运算符,这样,可以准确地看到
在程序运行过程中发生了什么事情

尽管程序没有显式地删除原始指针,但是在栈分解的时候,pMyObject对象
的析构函数会删除原始指针

输出
Allocating TraceHeap object on the heap at address 00FE49A0
5

这个我用cmd的方式进去的,会保留,如果只用vs里面的下面这句不会出现
Deleting TraceHeap object at address 00F5AA98

auto_ptr类模板可以很容易地用于指针数据成员

猜你喜欢

转载自blog.csdn.net/eyetired/article/details/81570204