g++4.8.2上列表方法参数默认初始化时出错

error on g++ 4.8.2 at list method-argument default initialization

本文关键字:默认 初始化 出错 参数 方法 列表 g++4      更新时间:2023-10-16

我正在尝试c++11的新功能,发现了一个问题。这是我的代码:

#include <iostream>
#include <list>
#include <string>
using namespace std;
class A {
public:
        int f (list<string> a, list<string> b={})
        {
            cout << a.size() << endl;
            cout << b.size() << endl; // This line!!!
            return 0;
        }
};
int main ()
{
    A a;
    list<string> l{"hello","world"};
    a.f(l);
    return 0;
}

执行死刑时,"这一行!!"。我继续调试,看起来问题就在这里。

       /**  Returns the number of elements in the %list.  */
       size_type
       size() const _GLIBCXX_NOEXCEPT
       { return std::distance(begin(), end()); }

我用这种方式编译我的程序:

g++ -std=c++11 -ggdb3 -fPIC -o test TestlistInit.cpp

我正在使用这个版本的g++:

g++ (Ubuntu 4.8.2-19ubuntu1) 4.8.2

提前感谢!!!

要找到原因,请启用调试符号,当您到达第一行时,我们首先检查b的内容,它看起来是这样的(值会不同)。在这种情况下,我使用了Code::Blocks"Watch"选项。

b.M_Impl._M_node._M_next = 0x7fffffffe370
b.M_Impl._M_node._M_prev = 0x7fffffffe370

然后使用调试器选项在我们到达b.size行时"单步执行"。

最终,我们将使用stl_iterator_base_funcs.h

一开始我们可以先看到&最后一个相同:

__first._M_node = 0x7fffffffe370
__last._M_node = 0x7fffffffe370
 while (__first != __last)
{
  ++__first;
  ++__n;
}

进入++__first,我们可以在stl_list.h:中看到它是这样做的

_Self&
operator++()
{
_M_node = _M_node->_M_next;
return *this;
}

_M_node_M_node->_M_next是相同的,所以__first从不递增,而.size()处于无休止的循环中。