Search code examples
c++if-statementshared-ptrshort-circuiting

about order of evaluation using shared pointers


I have a doubt about the order of evaluation in a if-clause when using shared pointers.

Suppose I have the following

struct MyClass {
   bool canUse(){ return false; } // dummmy value
}

std::shared_ptr<MyClass> myclass_ptr_;

/// other code..

if(myclass_ptr_ && myclass_ptr_->canUse()) {
   // do something
}

Do you know if in that case C++ always guarantees that myclass_ptr_ is evaluated before myclass_ptr_->canUse() ?

If it is not always the case and myclass_ptr_ might come after for some reason and it is not initialised I am risking to surely crash the app.

When I run this app it seems working fine, but I just want to confirm with someone to avoid nasty surprises in a release.


Solution

  • Do you know if in that case C++ always guarantees that myclass_ptr_ is evaluated before myclass_ptr_->canUse() ?

    Yes. This case doesn't fall under order of evaluation but short circuiting rule for &&.

    From foot note on this page.

    Builtin operators && and || perform short-circuit evaluation (do not evaluate the second operand if the result is known after evaluating the first), but overloaded operators behave like regular function calls and always evaluate both operands

    Also read Why there is no circuiting when these operators are overloaded.