Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
338 views
in Technique[技术] by (71.8m points)

c++ - 立即通过其成员时右值的范围(Scope of rvalue when immediately passing its member)

When does an rvalue get invalidated/is considered undefined?

(右值什么时候失效/被认为是未定义的?)

Below are two examples, one of which the rvalue is stored in a local variable and then actions on that local variable are performed, the other example shows a member of the rvalue being passed immediately to a function which also operates on the data.

(下面是两个示例,其中一个rvalue存储在一个局部变量中,然后对该局部变量执行操作,另一个示例显示该rvalue的成员立即传递给对数据进行运算的函数。)

I suspect example 1 is undefined behaviour, as in my own code (this is a minimal reproducible example), the application completely fails, meanwhile 2 does not.

(我怀疑示例1是未定义的行为,因为在我自己的代码中(这是最小的可复制示例),应用程序完全失败,而2则没有。)

Is 2 also undefined behaviour?

(2也是不确定的行为吗?)

Which of the examples are?

(哪个例子是?)

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

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

    // ... do stuff with data
}

vs

(与)

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);
}
  ask by super translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The 2nd one is well-formed.

(第二个是格式正确的。)

Temporaries will be destroyed after the full expression.

(完整表达后, 临时文件将被销毁。)

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

(所有临时对象均被销毁,这是评估(按词法)包含创建它们的点的完整表达式的最后一步,...)

Given do_stuff_with_data(container(123).data);

(给定do_stuff_with_data(container(123).data);)

, the temporary object (ie container(123) ) will be destroyed after the full expression, which contains the invocation of do_stuff_with_data .

(,则临时对象(即container(123) )将在完整表达式之后被销毁,该完整表达式包含对do_stuff_with_data的调用。)

On the other hand the 1st one might have undefined behavior.

(另一方面,第一个可能具有未定义的行为。)

After the full expression the temporary object has been destroyed and arr becomes dangled.

(在完整表达式之后,临时对象已被破坏, arr挂了起来。)

Any dereference on it later leads to UB.

(以后对其进行任何取消引用都将导致UB。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...