【问题标题】:error on g++ 4.8.2 at list method-argument default initializationg++ 4.8.2 在列表方法参数默认初始化时出错
【发布时间】:2014-12-26 17:41:09
【问题描述】:

我正在尝试 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

提前谢谢!!!

【问题讨论】:

  • 我在 4.7.3 上遇到了同样的问题,有趣的是只是替换 list&lt;string&gt; b = list&lt;string&gt;() 有效。但是,是的,似乎是一个 gcc 错误。
  • 绝对是一个错误。当您从函数中将它作为默认参数返回时,您会得到一个 segmentation fault。看看会发生什么when the list contains elements.
  • 令人难以置信的是,4.8.2 中仍然存在这样的基本错误 ...
  • 这似乎适用于 g++ 4.9.1(在 Debian 上)

标签: c++ list c++11 initialization


【解决方案1】:

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

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

然后在我们点击 b.size 行后使用调试器选项“Step into”。

最终这会将我们带到 stl_iterator_base_funcs.h

一开始我们可以看到 first 和 last 是一样的:

__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-&gt;_M_next 是相同的,所以__first 永远不会增加,.size() 会陷入无限循环。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-19
    • 2021-11-27
    • 1970-01-01
    • 2015-02-25
    • 1970-01-01
    • 2021-07-28
    • 2014-05-06
    • 1970-01-01
    相关资源
    最近更新 更多