主要内容:
- 标准C++ string类
- 模板auto_ptr、unique_ptr和shared_ptr
- 标准模板库(STL)
- 容器类
- 迭代器
- 函数对象(functor)
- STL算法
- 模板initializer_list(C++11)
2. 智能指针模板类
智能指针是行为类似于指针的类对象。本节介绍三个可帮助管理动态内存分配的智能指针模板。
先来看需要哪些功能已经这些功能是如何实现的:
void remodel(std::string& str)
{
std::string* ps = new std::string(str);
//...
str = *ps;
return;
}
如果ps不是一个普通指针,而是一个对象,则可以在对象过期时,让它的析构函数删除指向的内存。这正是auto_ptr、unique_ptr、shared_ptr背后的思想。模板auto_ptr是C++98提供的解决方案,C++11已经将其摈弃,并提供了另外两种解决方案。然而,auto_ptr已经使用了多年,如果编译器不支持其他两种解决方案,auto+ptr将是唯一的选择。
2.1 使用智能指针
三个智能指针模板(auto_ptr、unique_ptr、shared_ptr)都定义了类似指针的对象,可以将new获得(直接或间接)的地址赋给这种对象。当智能指针过期时,其析构函数将使用delete来释放内存。
要创建智能指针对象,必须包含头文件memory,该文件包含模板定义。然后使用通常的模板语法来实例化所需类型的指针。
例如,模板auto_ptr包含如下构造函数:
template<class X>
class auto_ptr
{
public:
explicit auto_ptr(X* p = 0) throw(); //throw()意味着构造函数不会引发异常;与auto_ptr一样,throw()也被摈弃
//...
};
请求X类型的auto_ptr将获得一个指向X类型的auto_ptr:
auto_ptr<double> pd(new double);
auto_ptr<string> ps(new string);
unique_ptr<double> pdu(new double);
shared_ptr<string> pss(new string);
因此,要转换remodel()函数,应按下面3个步骤进行:
1. 包含头文件memory;
2. 将指向string的指针替换为指向string的智能指针对象;
3. 删除delete语句
#include <memory