一、概念总体理解
即通过存在于栈区的对象的生命周期,控制存在于堆区的存储空间的生命周期。防止内存泄露。
二、类别
2.1 auto_ptr
auto_ptr可以实现最基础的栈区对象控制堆区内存生命周期控制。
// 示例一、
#include <iostream>
using namespace std;
class Test
{
public:
Test() {
printf("Test() call\n");
}
~Test() {
printf("~Test() call\n");
}
};
void fun()
{
auto_ptr<Test> p1(new Test());
printf("step1: %p\n", p1.get());
auto_ptr<Test> p2 = p1;
printf("step2: %p\n", p1.get());
printf("step3: %p\n", p2.get());
}
int main(int argc, const char * argv[]) {
printf("fun() call\n");
fun();
printf("fun call end\n");
return 0;
}
// 输出结果为:
fun() call
Test() call
step1: 0x100657230
step2: 0x0
step3: