9

Is it safe to dereference a temporary std::shared_ptr?

Example:

std::shared_ptr<std::string> create_shared_string()
{
  return std::shared_ptr<std::string>(new std::string("hello"));
}

std::cout << *create_shared_str() << std::endl;

My fear is that the shared_ptr is destroyed and the reference counter goes to zero as soon as the dereference is complete and thus the returned raw pointer is no longer safe.

monoceres
  • 4,722
  • 4
  • 38
  • 63

1 Answers1

7

what is the lifetime of C++ temporary object

in this case, the returned std::shared_ptr will not be destructed until std::cout << std::endl; is finished, so you can dereference it safely.

Community
  • 1
  • 1
yngccc
  • 5,594
  • 2
  • 23
  • 33