Calling non-static member function outside of object's lifetime in C++17

前端 未结 5 1671
无人及你
无人及你 2021-02-03 22:06

Does the following program have undefined behavior in C++17 and later?

struct A {
    void f(int) { /* Assume there is no access to *this here */ }
};

int main(         


        
5条回答
  •  我在风中等你
    2021-02-03 22:44

    The postfix expression a->f is sequenced before the evaluation of any arguments (which are indeterminately sequenced relative to one another). (See [expr.call])

    The evaluation of the arguments is sequenced before the body of the function (even inline functions, see [intro.execution])

    The implication, then is that calling the function itself is not undefined behavior. However, accessing any member variables or calling other member functions within would be UB per [basic.life].

    So the conclusion is that this specific instance is safe per the wording, but a dangerous technique in general.

提交回复
热议问题