Why can std::map::emplace usage leak memory?

  • A+
Category:Languages

In a recent article I read that the following use of std::map::emplace might leak memory, but I do not see why:

// might leak if allocation fails due to insufficient memory for an object A std::map<int, std::unique_ptr<A>> m; m.emplace(1, std::make_unique<A>("Ann",63)); 

Can anybody explain?

 


The snippet you've posted will not cause a memory leak if say the allocation of a new node by the map fails due to low memory. You've constructed a unique_ptr before calling map::emplace, so if that function throws, the unique_ptr will delete A and avoid a leak.

What the author presumably means is the following code will leak memory under similar conditions

std::map<int, std::unique_ptr<A>> m; m.emplace(1, new A("Ann",63)); 

In this case you're passing a raw pointer to emplace and relying on the function to transfer ownership of the pointer to a unique_ptr. If the function throws during the allocation of a new node, no unique_ptr would've been constructed to take ownership of the pointer and the memory will be leaked.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: