4

Apologies if this is a duplicate.. Hopefully it is not. I searched through a long list of questions, but they all seemed to not really explain it.

Here goes: In the follwoing

int main(int,char**){
    auto a = make_unique<std::string>("Hello World");

    // do stuff with either &*a or a.get()

    return 0;
}

is there any difference between &*a and a.get() ? I know they both return the raw pointer value (unless operator& is overloaded), but are there any runtime advantages to picking one over the other?

Lightness Races in Orbit
  • 369,052
  • 73
  • 620
  • 1,021
Born2Smile
  • 2,810
  • 1
  • 17
  • 18

1 Answers1

6

&*a is undefined behavior if the pointer is nullptr. You can learn more about undefined behavior here.

In all other cases I'd expect both solutions to be quite equivalent. I would prefer to use get() because this is the direct way which everyone understands.

From the C++ Standard:

20.9.1.2.4 unique_ptr observers [unique.ptr.single.observers]

typename add_lvalue_reference::type operator*() const;
1 Requires: get() != nullptr.
2 Returns: *get().

Werner Henze
  • 15,667
  • 12
  • 43
  • 65
  • +1 for the standards reference :) I tried compiling once with each.. `g++ -o test test.cpp`.. the binaries differ, so not quite the same, I guess. Not sure how to tell which is faster though.. – Born2Smile Apr 11 '16 at 11:50
  • 1
    @born2smile use the optimizer (-O) and compare –  Apr 11 '16 at 17:16
  • ah, indeed. With the optimizer the two compile to the same code. I wonder what consequence this has if `a` is `nullptr` – Born2Smile Apr 11 '16 at 21:45
  • @Born2Smile : The behavior of undefined behavior is undefined. ;-] – ildjarn Apr 15 '16 at 00:29