8

I'm using unique_ptr to manage some resources for safe destruction in every circumstance, etc.

void do_something(BLOB* b);
unique_ptr<BLOB> b(new_BLOB(20));

Is &* much worse than get? e.g.

do_something(&*b);

or

do_someting(b.get());

both seem to work.

2
  • That's pretty much comparable to using &* with an iterator.
    – Emil Laine
    Commented Oct 30, 2015 at 17:27
  • "worse" is subjective term, in what sense it is worse?
    – Slava
    Commented Oct 30, 2015 at 17:30

4 Answers 4

17

The operator* of std::unique_ptr has undefined behavior if no memory is owned by the unique_ptr where as get() will return nullptr.

If the unique_ptr could ever be empty I would suggest using get() otherwise there is no difference.

12

&*b is not necessarily equivalent to b.get(). In order to be sure to recieve a pointer to the managed object, you want to use get(). There are two reasons:

  • Calling operator* on a unique_ptr not managing any object is undefined behaviour
  • The managed object of type T may overload operator& and as such you may not recieve a valid pointer to T.

The standard defines the bevaiour of operator* of std::unique_ptr:

typename add_lvalue_reference<T>::type operator*() const;

  1. Requires: get() != nullptr

  2. Returns: *get()

Thus, applying operator* (from &*) is not allowed if get() returns nullptr.

You will get the return value of any overloaded operator& in the managed object if present. This can be circumvented by using std::addressof but the undefined behaviour problem persists.

std::unique_ptr<T>::get() will give you the address of the managed object or nullptr if no object is managed. It is safer to use get() and you have a predictable result.

3

As has been pointed out by other answers, if the unique_ptr does not manage any object, use of &* leads to undefined behavior.

For cases where unique_ptr manages a pointer, in most cases,

do_something(&*b);

is equivalent to

do_someting(b.get());

The only time you could get different results is if BLOB has an operator& overload that returns a pointer that is different than the address of the object.

1

This is really an opinion based question.

I happen to think &*ptr looks ugly and it isn't clear to a reader why it is written like that. But it does have the advantage that it works with smart pointers and regular pointers.

2
  • That advantage can also be achieved by template specialisation or type traits. Commented Oct 30, 2015 at 17:33
  • 2
    Although you think it is an opinion based question, you gave a good technical reason for &* Commented Oct 30, 2015 at 18:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.