初识智能指针和标准模板库STL
智能指针
什么是智能指针
智能指针是行为类似于指针的类对象。
为什么要使用智能指针
在函数内使用常规普通指针时,容易因为忘记释放内存、异常使函数直接终止等原因造成内存泄露;考虑到类对象可以在对象过期时,析构函数会释放指向的内存,所以我们考虑将指针对象化,由此引出智能指针。当然,知道智能指针的目的后,我们得注意,智能指针的实质是行为类似于指针的类对象。
三个智能指针模板
分别是auto_ptr, unique_ptr, shared_ptr。
auto_ptr已被C++11摒弃,但它已使用多年;且编译器不支持其他两种智能指针时,auto_ptr是唯一的选择。
格式
要创建智能指针对象,必须包含头文件memory;模板位于名称空间std中。
#include <iostream>
#include <string>
#include <memory>
class Report
{
private:
std::string str;
public:
Report(const std::string s) : str(s){
std::cout << "Object created!\n";
}
~Report(){
std::cout << "Object deleted!\n";
}
void comment()const{
std::cout << str << std::endl;
}
};
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;
}
标准模板库(STL)
什么是STL
标准模板库(Standard Template Library),简称为STL。STL提供了一组表示容器、迭代器、函数对象和算法的模板。容器是一个与数组类似的单元,可以存储若干个值。STL容器是同质的,即存储的值的类型相同;迭代器能够用来遍历容器的对象,与能够遍历数组的指针类似,是广义指针;函数对象是类似于函数的对象,可以是类对象或函数指针(包括函数名)。STL使得能够构造各种容器(包括数组、队列和链表)和执行各种操作(包括搜索、排序和随机排列)。
参考书籍
《C++ Primer Plus》_第6版