3

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?

Pete Becker
  • 72,338
  • 6
  • 72
  • 157
Bill Kotsias
  • 3,038
  • 4
  • 32
  • 57
  • 4
    Probably the safe bool problem: https://en.cppreference.com/w/cpp/language/implicit_conversion#The_safe_bool_problem – UnholySheep Jan 18 '21 at 09:00

1 Answers1

7

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.

ネロク
  • 21,268
  • 3
  • 51
  • 67