2

I was wondering why the bool conversion operator of a shared_ptr works fine in an if-statement, but not in the implicit conversion to the (bool) return value..

std::shared_ptr<const OfflineContainer> m_pContainer;   

bool MyClass::IsInitialized() const
{
    if (m_pContainer) // compi;es
        return true;

    return m_pContainer; // won't compile
}

The compiler message: Error C2440 'return': cannot convert from 'const std::shared_ptr<const MyClass>' to 'bool'

Ben
  • 1,519
  • 23
  • 39
  • 4
    It's because [the conversion operator](https://en.cppreference.com/w/cpp/memory/shared_ptr/operator_bool) is marked as `explicit`. That means you can't make implicit conversions (as is done in the `return` statement). – Some programmer dude Feb 21 '20 at 10:44
  • 1
    See also [When can I use `explicit operator bool` without a cast?](/q/39995573/4850040) – Toby Speight Feb 21 '20 at 12:06

0 Answers0