C++智能指针简单剖析
导读最近在补看《C++ Primer Plus》第6版,这的确是本好书,其中关于智能指针的章节解析的非常清晰,1解我之前的多处困惑。C++面试进程中,很多面试官都喜欢问智能指针相干的问题,比如你知道哪些智能指针?shared_ptr的设计原理是甚么?如果让你自己设计1个智能指针,你如何完成?等等……。而且在看开源的C++项目时,也能随处看到智能指针的影子。这说明智能指针不但是面试官爱问的题材,更是非常有实用价值。 下面是我在看智能指针时所做的笔记,希望能够解决你对智能指针的1些困扰。 目录
正文1. 智能指针背后的设计思想我们先来看1个简单的例子: void remodel(std::string & str)
{
std::string * ps = new std::string(str);
...
if (weird_thing())
throw exception();
str = *ps;
delete ps;
return;
} 当出现异常时(weird_thing()返回true),delete将不被履行,因此将致使内存泄漏。 这正是 auto_ptr、unique_ptr和shared_ptr这几个智能指针背后的设计思想。我简单的总结下就是:将基本类型指针封装为类对象指针(这个类肯定是个模板,以适应不同基本类型的需求),并在析构函数里编写delete语句删除指针指向的内存空间。 因此,要转换remodel()函数,应按下面3个步骤进行:
下面是使用auto_ptr修改该函数的结果: # include <memory>
void remodel (std::string & str)
{
std::auto_ptr<std::string> ps (new std::string(str));
...
if (weird_thing ())
throw exception();
str = *ps;
// delete ps; NO LONGER NEEDED
return;
} 2. C++智能指针简单介绍STL1共给我们提供了4种智能指针:auto_ptr、unique_ptr、shared_ptr和weak_ptr(本文章暂不讨论)。 使用注意点
使用举例 #include <iostream>
#include <string>
#include <memory>
class report
{
private:
std::string str;
public:
report(const std::string s) : str(s) {
std::cout << "Object created.
";
}
~report() {
std::cout << "Object deleted.
";
}
void comment() const {
std::cout << str << "
";
}
};
int main() {
{
std::auto_ptr<report> ps(new report("using auto ptr"));
ps->comment();
}
{
std::shared_ptr<report> ps(new report("using shared ptr"));
ps->comment();
}
{
std::unique_ptr<report> ps(new report("using unique ptr"));
ps->comment();
}
return 0;
} 3. 为何摒弃auto_ptr?先来看下面的赋值语句: auto_ptr< string> ps (new string ("I reigned lonely as a cloud.”);
auto_ptr<string> vocation;
vocaticn = ps; 上述赋值语句将完成甚么工作呢?如果ps和vocation是常规指针,则两个指针将指向同1个string对象。这是不能接受的,由于程序将试图删除同1个对象两次――1次是ps过期时,另外一次是vocation过期时。要避免这类问题,方法有多种:
|