28

I'm switching to GCC 4.6.1, and it starts to complain about code which works fine with GCC 4.4 and MSVC10. It seems that it doesn't want to convert between shared_ptr and bool when returning from a function like this:

class Class { shared_ptr<Somewhere> pointer_; };

bool Class::Function () const
{
    return pointer_;
}

using

return static_cast<bool> (pointer_);

everything works. What the heck is going on? This is with --std=cpp0x.

Anteru
  • 18,283
  • 10
  • 72
  • 117

2 Answers2

44

In C++11, shared_ptr has an explicit operator bool which means that a shared_ptr can't be implicitly converted to a bool.

This is to prevent some potentially pitfalls where a shared_ptr might accidentally be converted in arithmetic expressions and the similar situations.

Adding an explicit cast is a valid fix to your code.

You could also do return pointer_.get() != 0;, return pointer_.get(); or even return pointer_ != nullptr;.

CB Bailey
  • 648,528
  • 94
  • 608
  • 638
  • 10
    @LucDanton: For no rational reason, I completely dislike that method but yes, it also works. – CB Bailey Sep 28 '11 at 08:09
  • To be quite honest I mentioned it because it preceded explicit conversions operators and contextual conversions. – Luc Danton Sep 28 '11 at 08:12
  • @LucDanton If you like obfuscation, yes. What you'd really like to write is either `return pointer != NULL;` or `return pointer.is_valid();` or something similar. Regretfully, neither Boost nor the standards committee decided to support this, so your stuck with `return pointer.get() != NULL'`. – James Kanze Sep 28 '11 at 08:26
  • Sorry for the long kick. Why not return pointer_.is_initialized() ? – RvdK Mar 13 '19 at 12:37
3

shared_ptr has an explicit bool conversion. It can be used in a conditional expression or can be explicitly converted to bool as you did with static_cast.

hansmaad
  • 16,551
  • 7
  • 46
  • 89