Error in g ++ 4.8.2 when initializing the list argument method by default

I am trying to take advantage of the new features of C ++ 11 and I have found a problem. This is my code:

#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"}; af(l); return 0; } 

performance stuck in "This line !!!" line. I am continuing debugging and it looks like the problem is here.

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

I will compile my program as follows:

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

I am using this version of g ++:

 g++ (Ubuntu 4.8.2-19ubuntu1) 4.8.2 

thanks in advance!

+6
source share
1 answer

To find the reason, turn on debugging symbols, and when you get to the first line, first check the contents of b, which looks like this (the value will differ). In this case, I used Code :: Blocks "Watch", an option.

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

Then use the debugger option for "Stand up" as soon as we click on our line b.size.

In the end, this will lead us to stl_iterator_base_funcs.h

In the beginning we see that the first and last are the same:

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

Entering ++__first , we see that he does this in stl_list.h:

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

_M_node and _M_node->_M_next same, so __first never grows, and .size() gets into an infinite loop.

+2
source

Source: https://habr.com/ru/post/977479/


All Articles