本文介绍了智能指针auto_ptr的基本概念和简单的使用方法,以及示例程序。然后根据智能指针的使用特点,自己定义了一个智能指针的模板类。以加深对智能指针的理解。
auto_ptr保证在异常被抛出时,分配的对象能够自动消费,内存能够自动释放。使用auto_ptr可以代替指针进行操作,并且不关心内存的释放。解决内存溢出的问题。
下面的程序包括auto_ptr一个简单的示例一级自定义的一个类模板smart_pointer,以便链接智能指针的底层实现的原理:
测试源代码
#include "stdafx.h"
#include <iostream>
#include <string>
#include <memory>
#pragma warning(disable:4996)
using namespace std;
class test{
public:
char *name;
test(){
cout << "constructor have not arg" << endl;
name = NULL;
}
test(const char* str_name)
{
cout << "constructor have arg" << endl;
name = new char[strlen(str_name) + 1];
strcpy(name, str_name);
}
test& operator = (const char *str_name)
{
cout << "= overload" <<endl;
if (NULL != name)
delete name;
name = new char[strlen(str_name) + 1];