智能指针
参考书录:Effective Modern C++ 第四章 智能指针
1. unique_ptr
条款18:使用unique_ptr管理具备专属所有权的资源
unique_ptr比auto_ptr更为高级,使用移动语义实现了原对象的置空,以下是一个例子:
class A {
public:
A() {}
A(const A&) = delete;
A(A&&) { std::cout << "move construction" << std::endl; }
};
A makeA() { A a; return a; }
int main()
{
auto a = makeA();
return 0;
}
其输出为:
move construction
使用移动构造函数可以使得临时变量被转移至函数体外而不析构,以下为以unique_ptr为例子的工厂函数。若析构器是函数指针,那么unique_ptr的尺寸一般会增加一到两个字长。若为函数对象则取决于其中存储多少状态。无状态的函数对象(例如,无捕获的lambda表达式)不会浪费任何存储尺寸。
auto delInvmt = [](Investment* inv) {
inv->logging();
delete inv;
};
template<typename ...Args>
tinySTL::unique_ptr<Investment, decltype(delInvmt)>
makeInvestment(INVTYPE type, Args&&... args) {
tinySTL::unique_ptr<Investment, decltype(delInvmt)>
pInv(nullptr, delInvmt);
if (type == INVTYPE::STOCK) {
pInv.reset(new Stock(tinySTL::forward<Args>(args)...));
}
else if (type == INVTYPE::BOND) {
pInv.reset(new Bond(tinySTL::forward<Args>(args)...));
}
else if (type == INVTYPE::REALESTATE) {
pInv.reset(new RealEstate(tinySTL::forward<Args>(args)...));
}
return pInv;
}
这里有一个问题,就是当delInv为函数对象时出现“类模板的成员无法获取函数类型”问题。这是函数指针和函数对象类型