C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了C堆栈内存仍然有效?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
如果我在堆栈上创建一个对象并将其推入列表中,那么该对象将失去作用域(在下面的示例中的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 *>我的列表;而不是列表…在这种情况下它会无效吗?

解决方法

所有容器都会复制它们存储的内容.如果要在容器中使用对象,则要求对象是可复制构造和可分配的.

所以是的,矢量,列表等都是你的对象的副本.

一个更短的例子:

struct foo {};
std::vector<foo> v;

v.push_BACk(foo()); 
// makes a copy of the temporary,which dies at the semicolon.

如果它没有复制,上面的@L_944_6@就会很糟糕.

以下@L_944_6@不正常:

struct foo {};
std::vector<foo*> v;

{
    foo f;
    v.push_BACk(&f); // fine,but...
} // ...Now f stops exisTing and...

v.front(); // ...points to a non-existent object.

大佬总结

以上是大佬教程为你收集整理的C堆栈内存仍然有效?全部内容,希望文章能够帮你解决C堆栈内存仍然有效?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。