英文:
Why do I get the "correct" output despite accessing an object that went ouf of scope?
问题
以下是您要翻译的内容:
#include <iostream>
class Test1 {
public:
int a;
};
class Test2 {
public:
Test1* ptr;
};
void assign(Test2& t2) {
Test1 t1{10};
t2.ptr = &t1;
}
int main() {
Test2 t2;
assign(t2);
std::cout << t2.ptr->a << std::endl;
return 0;
}
如果您需要进一步的解释或有其他问题,请随时提出。
英文:
The code below will print 10
, but the t1
object (created in the function assign
) no longer exists by the time the print happens, so is the ptr
pointer pointing to unallocated memory space that still holds the value 10?
#include <iostream>
class Test1 {
public:
int a;
};
class Test2 {
public:
Test1* ptr;
};
void assign(Test2& t2) {
Test1 t1{10};
t2.ptr = &t1;
}
int main() {
Test2 t2;
assign(t2);
std::cout << t2.ptr->a << std::endl;
return 0;
}
答案1
得分: 2
提供的代码示例展示了可能存在的访问不再有效的内存的潜在问题。在assign
函数中,创建了一个局部变量t1
,并将其地址分配给了对象t2
的ptr
成员。然而,t1
在assign
函数结束时被销毁,导致t2.ptr
指向一个无效的内存位置。在main
函数中访问t2.ptr
可能导致未定义的行为。为确保正确的行为,您需要确保由ptr
指向的对象的生存期超出了assign
的范围。
英文:
The provided code demonstrates a potential issue with accessing memory that may no longer be valid. In the assign
function, a local variable t1
is created and its address is assigned to the ptr
member of an object t2
. However, t1
is destroyed at the end of the assign
function, leaving t2.ptr
pointing to an invalid memory location. Accessing t2.ptr
in the main
function can lead to undefined behavior. To ensure correct behavior, you need to ensure the lifetime of the object pointed to by ptr
extends beyond the scope of assign
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论