Alexis Wilke Alexis Wilke - 1 year ago 74
C++ Question

Why can't I return a shared pointer in C++14 when the function return type is bool?

I'm using g++ and write a simple function:

#include <memory>

std::shared_ptr<char> ptr;

bool fails_compiling()
return ptr;

From what I can see in the interface, the
implementation includes a
operator and I can even apply a quick fix like this:

return static_cast<bool>(ptr);

And it now compiles.

Why would the return algorithm not attempt an auto-conversion to
like the

Answer Source

If you checkout std::shared_ptr's bool conversion operator, you will see that it's declared as:

explicit operator bool() const;

The use of explicit simply tells the compiler to forbid implicit conversion, which is what would have taken place because the return type of your function is different from the object type you are returning. However, this doesn't affect contextual conversions.

which occurs in the context of any:

  • controlling expression of if, while, for;
  • the logical operators !, && and ||;
  • the conditional operator ?:;
  • static_assert;
  • noexcept.

above quote cited from cppreference

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download