常用的程序设计习惯是动态配置记忆体就是将某记忆体位置丢给指标後当在不需使用时才用delete手动回收,但如果在这之前发生例外,就会产生记忆体泄漏(Memory leak)。C++标准函式库中有提供样板auto_ptr处理这种状况,
// Fig. 16.10: Fig16_10.cpp
// Demonstrating auto_ptr.
#include <iostream>
using std::cout;
using std::endl;
#include <memory>
using std::auto_ptr; // auto_ptr class definition
#include "Integer.h"
// use auto_ptr to manipulate Integer object
int main()
{
cout << "Creating an auto_ptr object that points to an Integer\n";
// "aim" auto_ptr at Integer object
auto_ptr< Integer > ptrToInteger( new Integer( 7 ) );
cout << "\nUsing the auto_ptr to manipulate the Integer\n";
ptrToInteger->setInteger( 99 ); // use auto_ptr to set Integer value
// use auto_ptr to get Integer value
cout << "Integer after setInteger: " << ( *ptrToInteger ).getInteger()
<< "\n\nTerminating program" << endl;
return 0;
} // end main
auto_ptr< Integer > ptrToInteger( new Integer( 7 ) );
// ptrToInteger是个auto_ptr< Integer >的样板指标指向Integer物件,一开始透过建构子初始化值为7
ptrToInteger->setInteger( 99 );
//这边是透过auto_ptr操作Integer的setInteger()方法故使用->箭头符号
( ptrToInteger ).getInteger()
//神奇操作来了,对指标auto_ptr进行运算(取值运算)取回了Integer物件故这里是用.(dot)
// *取值运算
// & 取址运算
Integer的原始码请参考: day30_example https://gitlab.com/Ted_Griffin771/cpp-book-report/-/tree/master/examples/day30_example
<<: [Day - 27] - Spring 环境管理思想与设计
>>: Day 30 - 完赛纪念~迎接"数位"与"绿色"双转型时代的来临
前言 从小到大我们都听过这样的一句话: 工欲善其事,必先利其器 ------ 书上写的 在我们开始执...
剩最後10篇了,一起加油! 我们通常都会一次存入多笔资料,在这时候搜寻以及排序就变得相当重要,若是做...
这几天我们来介绍一些工具,在之後实作专案时会很常用到 我们的app 常常需要一些来自後台的资料,像是...
今天开始进入我不熟悉der领域惹 首先是恶意程序分析篇, 身边有朋友工作是与恶意程序分析相关的, 本...
在开始使用 Framework 之前,我们还是得先看看有没有办法利用纯手工的方式,先来解决一些基本...