12

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?

Yogeshwer Sharma
  • 3,647
  • 5
  • 25
  • 27

2 Answers2

15

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.

Mankarse
  • 39,818
  • 11
  • 97
  • 141
  • Mankarse: What is this syntax `operator unspecified-bool-type()`. I haven't seen this before. Is this something special to boost? – Yogeshwer Sharma Aug 29 '11 at 06:34
  • unspecified-bool-type is just a stand in for an actual type, such as bool. This syntax is not a special boost thing, it is the syntax for declaring a "type conversion operator". See [wikibooks](http://en.wikibooks.org/wiki/C++_Programming/Operators/Operator_Overloading#Conversion_operators) – Mankarse Aug 29 '11 at 06:39
  • Mankarse: Awesome. Thanks for the link. – Yogeshwer Sharma Aug 29 '11 at 06:43
2

shared_ptr has operator bool(), which returns true if it is not empty.

For example, this is Microsoft implementation of shared_ptr::operator bool(): http://msdn.microsoft.com/en-us/library/bb982901.aspx

shared_ptr::operator boolean-type - Tests if an owned resource exists.

Alex F
  • 42,307
  • 41
  • 144
  • 212
  • 1
    That is only conceptually correct, but not actually: http://www.artima.com/cppsource/safebool.html; but it's to be fixed with explicit conversion operators: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2435.htm – Sebastian Mach Aug 29 '11 at 07:24