您的位置:首页 > 编程语言 > C语言/C++

C++ 智能指针

2016-06-17 16:53 274 查看
A smart pointer is a class object that acts like a pointer but has addiction features. --《C++ Primer》第六版

一、使用普通指针的问题

1) 每次调用 remodel,动态分配内存,最后没有释放该资源,将导致memory leak.

void remodel(std::string& str)
{
std::string* ps = new std::string(str);//动态分配内存
...
str = ps;
return;
}


2) 即使最后释放资源,但是在中间抛出异常,则delete 语句无法执行,仍导致memory leak.

void remodel(std::string& str)
{
std::string* ps = new std::string(str);//动态分配内存
...
if(weird_thing())//抛出异常
throw_exception();
str = *ps;
delete ps;//释放动态分配的内存
return;
}


二、智能指针使用实例

主要有三种智能指针,auto_ptr/unique_ptr/shared_ptr。定义一个指向类A的智能指针pA:auto_ptr<A> pA(new A)。

#include <iostream>
#include <string>
#include <memory>
using namespace std;

int main()
{
//files:一个包含5个string 对象的数组
auto_ptr<string> files[5] =
{
auto_ptr<string> (new string("Fowl balls")),
auto_ptr<string> (new string("Duck Walks")),
auto_ptr<string> (new string("Chicken Runs")),
auto_ptr<string> (new string("Turkey Errors")),
auto_ptr<string> (new string("Goose Eggs"))
};

auto_ptr<string> pwin;
pwin = files[2]; //files[2] 失去对象的ownership
cout << "The nominees for best avian baseball film are\n";
for (int i = 0; i < 5; i++)
cout<<*files[i]<<endl;
cout<<"The winner is "<<*pwin<<"!\n";
return 0;
}


View Code
4) unique_ptr

当多个unique_ptr指向同一个对象,会产生编译错误

unique_ptr< string> pu1(new string "Hi ho!");
unique_ptr< string> pu2;
pu2 = pu1; //#1 not allowed
unique_ptr<string> pu3;
pu3 = unique_ptr<string>(new string "Yo!"); //#2 allowed


unique_ptr可以使用new[](delete[])。The auto_ptr template uses delete, not delete [], so it can only be used with new, not with new []. But unique_ptr has a new[], delete[] version: std::unique_ptr< double[]>pda(new double(5)); // will use delete []

五、如何选择智能指针

1) shared_ptr

程序里需要用多个指针指向同一个对象。比如:拥有一个数组指针,且需要标识出一些特别的元素(最大/最小);有两个对象都需要指向第三个类的对象;使用STL容器,容器的对象为指针。

2) unique_ptr

程序里不需要多个指针指向同一个对象。比如:把unique_ptr 作为函数的返回值,它指向一块动态分配的内存。

unique_ptr<int> make_int(int n){
return unique_ptr<int>(new int(n));
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: