为什么我访问了一个已经超出范围的对象,却得到了“正确”的输出?

huangapple go评论58阅读模式
英文:

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 &lt;iostream&gt;

class Test1 {
public:
     int a;
};

class Test2 {
public:
     Test1* ptr;
};

void assign(Test2&amp; t2) {
     Test1 t1{10};
     t2.ptr = &amp;t1;
}

int main() {
     Test2 t2;
     assign(t2);
     std::cout &lt;&lt; t2.ptr-&gt;a &lt;&lt; std::endl;
     return 0;
}

答案1

得分: 2

提供的代码示例展示了可能存在的访问不再有效的内存的潜在问题。在assign函数中,创建了一个局部变量t1,并将其地址分配给了对象t2ptr成员。然而,t1assign函数结束时被销毁,导致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.

huangapple
  • 本文由 发表于 2023年6月9日 05:45:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76435892.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定