Search code examples
c++pointersmemory-addresstemporary

Is assigning to a field of temporary object undefined behavior?


I compiled the following code with gcc and clang with -O1 and -std=c++20 flags, and it seems to work as expected.

#include <iostream>

struct S { int i; };

template<typename T>
T *get_address(T&& t) { return &t; }

void print_value_from_temporary(S *const s) {
    std::cout << s->i << '\n';
    s->i = 0;
    std::cout << s->i << '\n';
}

int main() {
    print_value_from_temporary(get_address(S{42}));
}

My question is: Is the s->i = 0; line an undefined behavior?


Solution

  • Is the s->i = 0; line an undefined behavior?

    No. The temporary will be destroyed after the full expression, which includes the execution of the function body of print_value_from_temporary. For s->i = 0; in print_value_from_temporary the temporary has not been destroyed yet.

    All temporary objects are destroyed as the last step in evaluating the full-expression that (lexically) contains the point where they were created,