As well as I understand, dereferencing - *smart_ptr
, and get()
+ dereferencing *smart_ptr.get()
doing the same thing with smart pointers, but may be there is something under the hood that I'm not aware of, cause I've seen a lot of cases there the second approach was used, so what is the point? Does it affect performance in any way?
From a functional standpoint, there is no difference between *smart_ptr
and *(smart_ptr.get())
, as they are defined in the C++ standard as doing the same thing - dereference the held pointer and return a reference to the object being pointed at.
However, from a debugging standpoint, there may be a subtle difference, depending on implementation. get()
is defined as returning the held pointer as-is, whether it is nullptr
or not. The smart pointer has no concept of what the caller will do with that pointer afterwards. However, dereferencing a nullptr
is undefined behavior, and knowing that, it is possible that a smart pointer implementation MAY decide to have its operator*
throw a runtime error if the held pointer cannot be dereferenced, to aid with debugging efforts.
This is mentioned on cppreference, at least for std::unique_ptr::operator*
:
may throw, e.g. if
pointer
defines a throwingoperator*