Scott Meyer的“Effective Modern C++”讨论了使用具有自定义删除器的
std::unique_ptr
,并指出:
例如,以下内容:函数指针作为删除器通常会导致
std::unique_ptr
的大小从一个字增长到两个字。对于函数对象作为删除器,则根据函数对象存储了多少状态而定。无状态函数对象(例如没有捕获的lambda表达式)不会产生大小惩罚,这意味着当自定义删除器可以实现为函数或无捕获lambda表达式时,应使用lambda表达式。
auto delInvmt1 = [](Investment* pInvestment) {
makeLogEntry(pInvestment);
delete pInvestment;
};
template<typename... Ts>
std::unique_ptr<Investment, decltype(delInvmt1)>
makeInvestment(Ts&&... args);
这段代码:
优于这段代码:
void delInvmt2(Investment* pInvestment) {
makeLogEntry(pInvestment);
delete pInvestment;
}
template<typename... Ts>
std::unique_ptr<Investment, void (*)(Investment*)>
makeInvestment(Ts&&... params);
我可以看到在第二种情况下,需要将删除器函数的指针存储在unique_ptr
中,但为什么在lambda情况下不需要存储类似的内容呢?
std::unique_ptr
使用空基类优化,这允许存储空对象(即没有数据成员的类)而不会增加额外的大小开销。 - milleniumbug