In C++, I can write something like:
shared_ptr<A> a_sp = someFunctionReturningSharedPtr();
if (a_sp) {
cout << a_sp->someData << endl;
} else {
cout << "Shared Pointer is NULL << endl;
}
Why does if (a_sp)
check work correctly? a_sp
is not a boolean, but how is it checked for true or false? How does the if condition know to check the result of a_sp.get()
function? Or if it does not, how is the NULL
ity of the a_sp
checked? Is there some function in shared_ptr
defined that converts it to boolean value?
So, we should use shared_ptr when we want to assign one raw pointer to multiple owners. // referring to the same managed object. When to use shared_ptr? Use shared_ptr if you want to share ownership of a resource.
Basically, shared_ptr has two pointers: a pointer to the shared object and a pointer to a struct containing two reference counts: one for "strong references," or references that have ownership, and one for "weak references," or references that don't have ownership.
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).
It is a reference counting ownership model i.e. it maintains the reference count of its contained pointer in cooperation with all copies of the std::shared_ptr. So, the counter is incremented each time a new pointer points to the resource and decremented when destructor of the object is called.
shared_ptr
has an operator unspecified-bool-type() const
that allows it to be used in boolean contexts. The unspecified-bool-type is typically defined as a pointer to function, or pointer to member-function, to disallow accidental matching to bool function overloads.
In C++0x
the idiom is to use explicit operator bool() const;
, which disallows implicit conversions (such as function calls, conversions to int
for arithmetic, and so on), but still allows the shared_ptr
to be converted to bool in boolean contexts.
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