智能指针是存储指向动态分配(堆)对象指针的类。除了能够在适当的时间自动删除指向的对象外,他们的工作机制很像C++的内置指针。智能指针在面对异常的时候格外有用,因为他们能够确保正确的销毁动态分配的对象。他们也可以用于跟踪被多用户共享的动态分配对象。
三种智能指针使用
包含头义件memory
#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 << "\n";
}
};
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;
}
如何选择智能指针
(1)如果程序要使用多个指向同一个对象的指针,应选择shared_ptr。这样的情况包括:
有一个指针数组,并使用一些辅助指针来标示特定的元素,如最大的元素和最小的元素;
两个对象包含都指向第三个对象的指针;
STL容器包含指针。
很多STL算法都支持复制和赋值操作,这些操作可用于shared_ptr,但不能用于unique_ptr(编译器发出warning)和auto_ptr(行为不确定)。如果你的编译器没有提供shared_ptr,可使用Boost库提供的shared_ptr。
(2)如果程序不需要多个指向同一个对象的指针,则可使用unique_ptr。如果函数使用new分配内存,并返还指向该内存的指针,将其返回类型声明为unique_ptr是不错的选择。这样,所有权转让给接受返回值的unique_ptr,而该智能指针将负责调用delete。可将unique_ptr存储到STL容器在那个,只要不调用将一个unique_ptr复制或赋给另一个算法(如sort())