While implementing a basic std library for my hobby OS I came across this and wondered why:
Both operator->()
and T* get()
are marked as noexcept, however operator*()
is not. According to the reference it should be equivalent to *get()
, which would allow it to be noexcept
and looking at some implementations I see no reason why it is not.
Why is unique_ptr
's dereferencing operator not marked as noexcept
?
The reset method can be utilised:class owner { std::unique_ptr<someObject> owned; public: owner() { owned. reset(new someObject()); } };
A unique_ptr can only be moved. This means that the ownership of the memory resource is transferred to another unique_ptr and the original unique_ptr no longer owns it. We recommend that you restrict an object to one owner, because multiple ownership adds complexity to the program logic.
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.
(since C++11) std::unique_ptr is a smart pointer that owns and manages another object through a pointer and disposes of that object when the unique_ptr goes out of scope. The object is disposed of, using the associated deleter when either of the following happens: the managing unique_ptr object is destroyed.
Because operator*
for the pointer
type of std::unique_ptr
may throw. The pointer
type alias is defined as:
std::remove_reference<Deleter>::type::pointer
if that type exists, otherwiseT
*. Must satisfy NullablePointer
That may be something other that T*
, it may be a class type that overloads operator*
.
From cppreference
typename std::add_lvalue_reference<T>::type operator*() const;
(1) (since C++11)pointer operator->() const noexcept;
(2) (since C++11)
And then:
Exceptions:
1) may throw, e.g. ifpointer
defines a throwingoperator*
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With