Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 529
Martin Avatar asked Dec 10 '22 04:12

Martin


1 Answers

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.

like image 187
Praetorian Avatar answered Jan 03 '23 07:01

Praetorian