gpt4 book ai didi

C++ 堆栈内存仍然有效吗?

转载 作者:太空狗 更新时间:2023-10-29 19:47:16 24 4
gpt4 key购买 nike

如果我在堆栈上创建一个对象并将其压入列表,那么该对象就会失去作用域(在下面示例中的 for 循环之外),该对象还会存在于列表中吗?如果列表仍然包含该对象,那么该数据现在是否无效/可能已损坏?

请让我知道,并请解释原因..

谢谢,jbu

class SomeObject{
public:
AnotherObject x;
}

//And then...
void someMethod()
{
std::list<SomeObject> my_list;
for(int i = 0; i < SOME_NUMBER; i++)
{
SomeObject tmp;
my_list.push_back(tmp);

//after the for loop iteration, tmp loses scope
}

my_list.front(); //at this point will my_list be full of valid SomeObjects or will the SomeObjects no longer be valid, even if they still point to dirty data
}

编辑:那如果它是 std::list<SomeObject*> my_list 又怎样呢? ;而不是列表...在那种情况下它会无效吗?

最佳答案

标准容器会复制对象,因此列表在您的示例中仍然可以。

关于C++ 堆栈内存仍然有效吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2656551/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com