1

I am learning shared_ptr in c++.

I have learned that I can check whether a shared_ptr has nullptr or not inside if sentence like

std::shared_ptr<int> sptr;
if ( sptr ) {
    std::cout << "sptr has a non-null pointer." << std::endl;
} else {
    std::cout << "sptr has a null pointer." << std::endl;
}

Now what I would like to do now is

bool NullCheck(std::shared_ptr<int>& sptr) {
    return sptr;  // I hoped that this works like inside if sentence.
}

However it does not work. Compiler tells me it cannot convert the shared_ptr to bool.

I can check whether the shared_ptr has nullptr or non-nullptr by the explicit comparison but I would like to know the way like inside if sentence. Someone who knows it is possible or not, please tell me.

mora
  • 2,217
  • 4
  • 22
  • 32
  • 1
    `bool NullCheck()` check can only return boolean values i.e `true` and `false`. You are returning a `shared_ptr` type, which is wrong. – Shravan40 Feb 11 '17 at 09:08
  • 1
    Does `return sptr == nullptr;` work? – Ed Heal Feb 11 '17 at 09:09
  • @Shravan40 The question is why is it wrong, when it works directly in an `if` statement. – juanchopanza Feb 11 '17 at 09:10
  • 2
    I'd add `const` to reference in `NullCheck` parameter - `bool NullChecker( const std::shared_ptr & sptr )`. Another *shugar* is to make this function templated: `template< typename T> bool NullChecker( const std::shared_ptr< T > & sptr) { return (bool)sptr; }` – borisbn Feb 11 '17 at 09:12
  • 2
    I'm not *convinced* the marked duplicate quite answers the question. The answer is that the conversion to `bool` in `shared_ptr` is marked `explicit`, and using it inside an `if` is considered an explicit conversion to `bool`, but returning from a `bool` function is not. You need to static cast `shared_ptr` to `bool`. – Martin Bonner supports Monica Feb 11 '17 at 11:20
  • @Martin Bonner : thank you for the answer I really wanted. – mora Feb 12 '17 at 10:14

0 Answers0