C++ Logo

std-discussion

Advanced search

Re: Member function release of std::unique_ptr

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Wed, 23 Jun 2021 19:12:27 -0400
On Wed, Jun 23, 2021 at 6:12 PM Robert A.H. Leahy via Std-Discussion
<std-discussion_at_[hidden]> wrote:
>
> That would produce a false positive on this snippet:
>
> std::vector<int*> v;
> // Assume there is machinery here that deletes
> // all pointers in v on scope exit
> auto ptr = std::make_unique<int>(5);
> v.push_back(ptr.get());
> ptr.release();

To clarify why this matters, `vector::push_back` can throw due to
allocation failure. So if you tried to do
`v.push_back(ptr.release())`, the object would never be deallocated.
You have to push it back first (where the aforementioned machinery
will take care of things), then release it.

Received on 2021-06-23 18:12:41