Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does shared_ptr work in if condition

Tags:

c++

shared-ptr

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 NULLity of the a_sp checked? Is there some function in shared_ptr defined that converts it to boolean value?

like image 339
Yogeshwer Sharma Avatar asked Aug 29 '11 06:08

Yogeshwer Sharma


People also ask

When should shared_ptr be used?

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.

What does a shared_ptr do?

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.

What happens when you move 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).

Is shared_ptr reference counting?

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.


1 Answers

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.

like image 73
Mankarse Avatar answered Nov 02 '22 22:11

Mankarse