Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GCC error: cannot convert 'const shared_ptr<...>' to 'bool' in return

Tags:

c++

gcc

c++11

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.

like image 209
Anteru Avatar asked Sep 28 '11 07:09

Anteru


1 Answers

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;.

like image 92
CB Bailey Avatar answered Sep 19 '22 11:09

CB Bailey