临时容器对象上的迭代器 [英] Iterators on temporary container object

查看:140
本文介绍了临时容器对象上的迭代器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个函数按值返回一个STL容器,例如std :: list

Suppose I have a function which returns a STL container by value, say std::list

std::list<Foo> get_Foolist()
{
    std::list<Foo> lst;
    //populate lst
    return lst;
}

class SomeClass
{
    std::list<Foo> get_Foolist()
    {
        return m_foolst;
    }
    ...
    private:
    std::list<Foo> m_foolst;
};

现在,我有一个代码片段,使用这个函数获取列表并迭代以下方式,

Now, I have a snippet of code which uses this function to get the list and iterate on it in following way,

std::list<Foo>::iterator i = get_Foolist().begin();
//use i like ... cout << *i << endl;

当我看到这个代码时,我觉得它不应该工作,因为我们使用迭代器临时对象它将在表达式执行后被删除。

When I saw this code, I felt it should not work since we are using iterator on a temporary object which will get deleted after expression is executed. But, to my surprise it was working.

这与Microsoft Visual Studio 2008的STLPort5.2配合使用。

This works with STLPort5.2 with Microsoft Visual Studio 2008.

稍后,当我们删除STLPort并开始使用编译器提供的STL实现时,我们开始面临崩溃。

Later, when we removed STLPort and started using STL implementation provided with compiler we started facing crashes at the point.

这表明上面的代码不能使用VS

It is revealed that code above doesn't work with VS 2008 list implementation but it works with the STLPort.

我尝试在各种其他编译器上运行它,结果如下,

I tried to run it on various other compilers and results were as follows,


  • Visual Studio 2008(无STLport5.2) - 崩溃

  • Visual Studio 2008(使用STLPort5.2) - 工作

  • Visual Studio 2013(无STLport5.2) - 崩溃

  • GCC 4.3.6(无STLPort5.2) - 工作

  • Clang 3.0(无STLPort5.2) - 工作

  • Visual Studio 2008 (Without STLport5.2) - Crashes
  • Visual Studio 2008 (With STLPort5.2) - Works
  • Visual Studio 2013 (Without STLport5.2) - Crashes
  • GCC 4.3.6 (Without STLPort5.2) - Works
  • Clang 3.0 (Without STLPort5.2) - Works

(GCC和Clang来自 http://melpon.org/wandbox/

(GCC and Clang were used from http://melpon.org/wandbox/)

现在我的问题是,


  1. 哪个实现是正确的(按标准)?

  2. 为什么它在VS ?


推荐答案



  1. 是正确的(按照标准)?


大概是所有的。



  1. 为什么在VS以外的所有实现上都成功?


这是 未定义的行为,因为您正在解除引用无效迭代器。所以它可以以无穷多种方式失败。或者似乎工作,这只是另一种失败模式。

It is undefined behaviour because you are de-referencing invalidated iterators. So it can fail in an infinite number of ways. Or appear to work, which is a just another mode of failure.

这篇关于临时容器对象上的迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆