7

Is it ok to dereference a shared pointer, assign and assign a new object to it like so:

void foo()
{
    std::shared_ptr<std::string> x =
            std::make_shared<std::string>();

    bar(*x); // is this fine?
    // x == bsl::string("WHATEVER")
}

void bar(string& y)
{
    y = string("whatever");
}
Martin F
  • 171
  • 1
  • 1
  • 10

1 Answers1

8

Yes, this is valid. Operator * returns the result of dereferencing the stored (raw) pointer.

Dereferencing a (raw) pointer does not make a copy or return a temporary: dereferencing a pointer when passing by reference

VLL
  • 9,634
  • 1
  • 29
  • 54