Alexis Wilke Alexis Wilke - 2 months ago 11
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
shared_ptr
implementation includes a
bool
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
bool
like the
if()
and
while()
do?

Answer

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