[libcxx-commits] [libcxx] [libc++] Mark std::unique_ptr::release() as nodiscard (PR #110847)
David Benjamin via libcxx-commits
libcxx-commits at lists.llvm.org
Wed Oct 2 08:37:35 PDT 2024
davidben wrote:
For the instances in BoringSSL, the context is that we need to interface with C APIs, and our C APIs often have this kinda annoying pattern:
```
// takes_ownership does some stuff. On success, it takes ownership
// of `thingy` and returns true. On failure, it returns false and the
// caller retains ownership of `thingy`.
bool takes_ownership(Thingy *thingy);
```
In C++, one would probably write this as taking `unique_ptr<Thingy>&&`, or just take `unique_ptr<Thingy>` by value and unconditionally take ownership. (It usually doesn't matter _who_ owns it on error, just someone does. APIs often look like this in C just because it's more natural to write it that way. Either way, the API is what it is and we're stuck with it.)
The best strategy I've come up with for that is:
```
unique_ptr<Thingy> thingy;
if (!takes_ownership(thingy.get())) {
return Error();
}
thingy.release(); // takes_ownership took ownership
```
Definitely not great, but works OK and does the right thing in both cases. But I don't mind adding a `(void)` in front or perhaps even a wrapper like `bssl::TookOwnership(thingy)`, I dunno. 🤷
https://github.com/llvm/llvm-project/pull/110847
More information about the libcxx-commits
mailing list