Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is unique_ptr operator* not noexcept? [duplicate]

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?

like image 508
Thalhammer Avatar asked Feb 01 '18 10:02

Thalhammer


People also ask

How to reset unique_ ptr in c++?

The reset method can be utilised:class owner { std::unique_ptr<someObject> owned; public: owner() { owned. reset(new someObject()); } };

Can you move a unique_ ptr?

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.

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.

What is a unique_ ptr in c++?

(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.


2 Answers

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, otherwise T*. Must satisfy NullablePointer

That may be something other that T*, it may be a class type that overloads operator*.

like image 185
StoryTeller - Unslander Monica Avatar answered Nov 06 '22 08:11

StoryTeller - Unslander Monica


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. if pointer defines a throwing operator*

like image 38
Jarod42 Avatar answered Nov 06 '22 09:11

Jarod42