关于使用共享指针的评估顺序

about order of evaluation using shared pointers

我对使用共享指针时 if 子句中的求值顺序有疑问。

假设我有以下内容

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

std::shared_ptr<MyClass> myclass_ptr_;

/// other code..

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

你知道在那种情况下 C++ 是否总是保证 myclass_ptr_myclass_ptr_->canUse() 之前求值吗?

如果情况并非总是如此,并且 myclass_ptr_ 可能由于某种原因出现并且未初始化,我冒着使应用程序崩溃的风险。

当我 运行 这个应用程序似乎工作正常时,但我只是想与某人确认以避免在发布中出现令人讨厌的意外。

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

是的。此案例不属于 &&.

order of evaluation but short circuiting 规则

来自脚注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

另请阅读Why there is no circuiting when these operators are overloaded