2

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.

Mohit Jain
  • 30,259
  • 8
  • 73
  • 100
Abruzzo Forte e Gentile
  • 14,423
  • 28
  • 99
  • 173
  • 1
    The Left operand of `&&` is always evaluated first. if `false`, the Right operand is not evaluated. Unless if you are using a user-defined overload of `&&` – WhiZTiM Feb 17 '17 at 11:09

1 Answers1

3

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.

Community
  • 1
  • 1
Mohit Jain
  • 30,259
  • 8
  • 73
  • 100