Scott Meyer’s “Effective Modern C++” discusses the use of std::unique_ptr
with custom deleter and states:
Deleters that are function pointers generally cause the size of a
std::unique_ptr
to grow from one word to two. For deleters that are function objects, the change in size depends on how much state is stored in the function object. Stateless function objects (e.g., from lambda expressions with no captures) incur no size penalty, and this means that when a custom deleter can be implemented as either a function or a captureless lambda expression, the lambda is preferable.
As an example, this:
auto delInvmt1 = [](Investment* pInvestment) {
makeLogEntry(pInvestment);
delete pInvestment;
};
template<typename... Ts>
std::unique_ptr<Investment, decltype(delInvmt1)>
makeInvestment(Ts&&... args);
is better than this:
void delInvmt2(Investment* pInvestment) {
makeLogEntry(pInvestment);
delete pInvestment;
}
template<typename... Ts>
std::unique_ptr<Investment, void (*)(Investment*)>
makeInvestment(Ts&&... params);
I can see that in the second case a pointer to the deleter function needs to be stored in the unique_ptr
, but why does nothing similar need to be stored for the lambda case?