加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C堆栈内存仍然有效?

发布时间:2020-12-16 10:16:43 所属栏目:百科 来源:网络整理
导读:如果我在堆栈上创建一个对象并将其推入列表中,那么该对象将失去作用域(在下面的示例中的for循环之外),该对象是否仍然存在于列表中?如果列表仍然保存对象,那么该数据现在是无效/可能已损坏吗? 请让我知道,请解释理由.. 谢谢, JBU class SomeObject{public:
如果我在堆栈上创建一个对象并将其推入列表中,那么该对象将失去作用域(在下面的示例中的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.

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

以下代码不正常:

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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读