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

Eze*_*lez 6 c++ initialization list c++11

我正在尝试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;
}
Run Code Online (Sandbox Code Playgroud)

执行停留在"这条线!!!" 线.我继续调试,看起来问题就在这里.

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

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

g++ -std=c++11 -ggdb3 -fPIC -o test TestlistInit.cpp
Run Code Online (Sandbox Code Playgroud)

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

g++ (Ubuntu 4.8.2-19ubuntu1) 4.8.2
Run Code Online (Sandbox Code Playgroud)

提前致谢!!!

Mal*_*ery 2

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

b.M_Impl._M_node._M_next = 0x7fffffffe370
b.M_Impl._M_node._M_prev = 0x7fffffffe370
Run Code Online (Sandbox Code Playgroud)

然后,一旦我们到达 b.size 行,就使用调试器选项“步入”。

最终这将带我们到 stl_iterator_base_funcs.h

一开始我们可以看到第一个和最后一个是相同的:

__first._M_node = 0x7fffffffe370
__last._M_node = 0x7fffffffe370

 while (__first != __last)
{
  ++__first;
  ++__n;
}
Run Code Online (Sandbox Code Playgroud)

进入++__first我们可以看到它在 stl_list.h 中执行此操作:

_Self&
operator++()
{
_M_node = _M_node->_M_next;
return *this;
}
Run Code Online (Sandbox Code Playgroud)

_M_node_M_node->_M_next是相同的,所以__first永远不会增加,并且.size()陷入无限循环。