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

前端 未结 5 1593
无人及你
无人及你 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:46

    You seem to assume that a->f(0) has these steps (in that order for most recent C++ standard, in some logical order for previous versions):

    • evaluating *a
    • evaluating a->f (a so called bound member function)
    • evaluating 0
    • calling the bound member function a->f on the argument list (0)

    But a->f doesn't have either a value or type. It's essentially a non-thing, a meaningless syntax element needed only because the grammar decomposes member access and function call, even on a member function call which by define combines member access and function call.

    So asking when a->f is "evaluated" is a meaningless question: there is no such thing as a distinct evaluation step for the a->f value-less, type-less expression.

    So any reasoning based on such discussions of order of evaluation of non entity is also void and null.

    EDIT:

    Actually this is worse than what I wrote, the expression a->f has a phony "type":

    E1.E2 is “function of parameter-type-list cv returning T”.

    "function of parameter-type-list cv" isn't even something that would be a valid declarator outside a class: one cannot have f() const as a declarator as in a global declaration:

    int ::f() const; // meaningless
    

    And inside a class f() const doesn't mean "function of parameter-type-list=() with cv=const”, it means member-function (of parameter-type-list=() with cv=const). There is no proper declarator for proper "function of parameter-type-list cv". It can only exist inside a class; there is no type "function of parameter-type-list cv returning T" that can be declared or that real computable expressions can have.

提交回复
热议问题