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.
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 ...).
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.
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With