Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 819
monoceres Avatar asked May 26 '13 19:05

monoceres


People also ask

Is shared_ptr thread safe?

std::shared_ptr is not thread safe. A shared pointer is a pair of two pointers, one to the object and one to a control block (holding the ref counter, links to weak pointers ...).

When should I use shared_ptr?

Use this option when the implied or explicit code contract between the caller and callee requires that the callee be an owner. Pass the shared_ptr by reference or const reference. In this case, the reference count isn't incremented, and the callee can access the pointer as long as the caller doesn't go out of scope.

What happens when shared_ptr goes out of scope?

The smart pointer has an internal counter which is decreased each time that a std::shared_ptr , pointing to the same resource, goes out of scope – this technique is called reference counting. When the last shared pointer is destroyed, the counter goes to zero, and the memory is deallocated.

What happens when you move a shared_ptr?

By moving the shared_ptr instead of copying it, we "steal" the atomic reference count and we nullify the other shared_ptr . "stealing" the reference count is not atomic, and it is hundred times faster than copying the shared_ptr (and causing atomic reference increment or decrement).


1 Answers

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.

like image 131
yngccc Avatar answered Oct 23 '22 13:10

yngccc