In C++, I can write something like:
shared_ptr a_sp = someFunctionReturningSharedPtr();
if (a_sp) {
cout << a_sp->someData << end
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.
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.