Are the following operations lockfree for std::unique_ptr
and/or std::shared_ptr
?
read(*myPtr)
or myPtr->getSomething()
std::move(myUniquePtr)
or when a std::shared_ptr
goes out of scope.In my case, I am not concurrently accessing these pointers from multiple threads. I'm just curious if I can use them exclusively on a high-priority, lockfree thread. The objects managed by the pointers were allocated by the main thread prior to the high-priority callbacks and will not be deallocated until the callbacks cease.
Thanks!
Yes, the control block is thread-safe; but no, the access to the resource is not thread-safe. That means, modifying the reference counter is an atomic operation and you have the guarantee that the resource will be deleted exactly once. These are all guarantees a std::shared_ptr gives you.
Smart pointers perform automatic memory management by tracking references to the underlying object and then automatically deleting that object when the last smart pointer that refers to that object goes away.
Introduction of Smart PointersC++11 comes up with its own mechanism that's Smart Pointer. When the object is destroyed it frees the memory as well. So, we don't need to delete it as Smart Pointer does will handle it.
As shown in the example, a smart pointer is a class template that you declare on the stack, and initialize by using a raw pointer that points to a heap-allocated object. After the smart pointer is initialized, it owns the raw pointer.
With a reasonable implementation, you can assume:
std::unique_ptr:
std::shared_ptr:
std::atomic<std::size_t>
(can be checked with the member function is_lock_free
).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