Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 571
Bill Kotsias Avatar asked May 14 '26 22:05

Bill Kotsias


1 Answers

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.

like image 199
ネロク・ゴ Avatar answered May 16 '26 12:05

ネロク・ゴ