Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is unique_ptr::release not defined with [[nodiscard]]?

C++17 added [[nodiscard]].

C++20 added the use of [[nodiscard]] on empty methods, e.g. vector::empty() -- maybe, to avoid user confusion with the method clear (i.e. calling empty() accidentally to clear the vector).

Why didn't C++20 use this opportunity to add [[nodiscard]] to unique_ptr::release?


Is there a valid reasonable scenario in which one would call unique_ptr::release without taking the returned value?


In the same manner of avoiding user confusion (if this was the reason for adding [[nodiscard]] to the empty methods) - the name release was always very confusing, sounds like, well... something is going to be released here.

Adding [[nodiscard]] could fix this name issue, in a way.

like image 581
Amir Kirsh Avatar asked Mar 04 '20 22:03

Amir Kirsh


People also ask

What does unique_ptr release do?

std::unique_ptr::releaseReleases ownership of its stored pointer, by returning its value and replacing it with a null pointer. This call does not destroy the managed object, but the unique_ptr object is released from the responsibility of deleting the object.

How to copy unique_ ptr c++?

A unique_ptr does not share its pointer. It cannot be copied to another unique_ptr , passed by value to a function, or used in any C++ Standard Library algorithm that requires copies to be made. A unique_ptr can only be moved.

What is use of unique_ ptr in c++?

Use unique_ptr when you want to have single ownership(Exclusive) of the resource. Only one unique_ptr can point to one resource. Since there can be one unique_ptr for single resource its not possible to copy one unique_ptr to another. A shared_ptr is a container for raw pointers.

How does unique_ ptr work?

A unique_ptr object wraps around a raw pointer and its responsible for its lifetime. When this object is destructed then in its destructor it deletes the associated raw pointer. unique_ptr has its -> and * operator overloaded, so it can be used similar to normal pointer.


Video Answer


2 Answers

This is addressed in the paper that added [[nodiscard]] to many of the functions. From P0600R1 this is the remark about adding [[nodiscard]] to unique_ptr::release()

Titus: at Google 3.5% of calls would fail, but analysis showed that it was correct (but weird ownership semantics). See reflector email.

like image 82
NathanOliver Avatar answered Oct 17 '22 03:10

NathanOliver


Because you've previously retrieved the pointer value and done stuff with it.

Simple approximation:

unique_ptr<someclass> ptr;
// ...
someclass *s = ptr.get();
if (s->are_we_there_yet()) {
    ptr.release();
    // finish up with s...
    s->close_garage_door();
    delete s;
}
like image 2
1201ProgramAlarm Avatar answered Oct 17 '22 03:10

1201ProgramAlarm