立即传递其成员时的右值范围

Scope of rvalue when immediately passing its member

什么时候右值 invalidated/is 被视为未定义?

下面是两个例子,其中一个右值存储在一个局部变量中,然后对该局部变量执行操作,另一个例子显示右值的一个成员被立即传递给一个函数,该函数也操作数据。

我怀疑示例 1 是未定义的行为,因为在我自己的代码中(这是一个最小的可重现示例),应用程序完全失败,同时 2 没有。 2 也是未定义的行为吗?以下是哪些例子?

struct container {
    int data[5];
    container(int a) {
        data[0] = a;
    }
};

void main() {
    int* arr = container(123).data;

    // ... do stuff with data
}

struct container {
    int data[5];
    container(int a) {
        data[0] = a;
    }
};

void do_stuff_with_data(int* data) {
    // ... do stuff with data
}
void main() {
    do_stuff_with_data(container(123).data);
}

第二个格式正确。 Temporaries 表达式满后销毁。

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

给定do_stuff_with_data(container(123).data);,临时对象(即container(123))将在包含do_stuff_with_data.

调用的完整表达式后销毁

另一方面,第一个可能有未定义的行为。在完整的表达式之后,临时对象被销毁并且 arr 变为悬挂状态。以后对它的任何取消引用都会导致 UB。