Search code examples
c++booleanshared-ptrimplicit-conversionreturn-type

Why isn't shared_ptr implicitly converted to boolean when returning it in a function?


The following won't compile:

#include <memory>
class A;
bool f() {
    std::shared_ptr<A> a;
    return a;
}

int main()
{
    f();
    return 0;
}

and fails with:

Compilation failed due to following error(s).main.cpp: In function ‘bool f()’:
main.cpp:13:12: error: cannot convert ‘std::shared_ptr’ to ‘bool’ in return
     return a;

What could be the reasoning of the standard (I presume) not allowing an implicit conversion here?


Solution

  • Because the user-defined operator for converting an std::shared_ptr to bool is explicit:

    explicit operator bool() const noexcept;
    

    Note that an implicit conversion to bool in the condition of an if statement – among others – still happens even with an explicit user-defined conversion operator to bool :

    std::shared_ptr<int> ptr;
    
    if (ptr) { // <-- implicit conversion to bool
    
    }
    

    That is, you don't need to write static_cast<bool>(ptr) in the condition of an if statement.