Re: iterators of a swapped std::list

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Wed, May 1, 2013 at 7:08 PM, Jonathan Wakely <jwakely.gcc@xxxxxxxxx> wrote:
> On 1 May 2013 17:45, Mihai Vasilian wrote:
>> Hi,
>> I have a question related to iterators of a swapped list.
>>
>> #include <list>
>> #include <stdio.h>
>> int main()
>> {
>>     int t[2]={-1,-2};
>>     std::list<int> l1(t, t+2), l2;
>>     std::list<int>::iterator beg=l1.begin(), end=l1.end();
>>     l1.swap(l2);
>>     for(; beg!=end; ++beg)
>>         printf("\n%d", *beg);
>>     return 0;
>> }
>>
>> $ gcc --version
>> gcc (GCC) 4.8.0 20130411 (prerelease)
>>
>> The program's output is:
>> -1
>> -2
>> 4195008
>> -1
>> -2
>> 4195008
>> -1
>> -2
>> 4195008
>> and it doesn't stop.
>>
>> I also tested GCC 4.7.3 with the same output.
>> Am I doing it wrong ?
>
> Yes.
>
> The standard says:
>
> "The expression a.swap(b), for containers a and b of a standard
> container type other than array, shall exchange the values of a and b
> [...] Every iterator referring to an element in one container before
> the swap shall refer to the same element in the other container after
> the swap. It is unspecified whether an iterator with value a.end()
> before the swap will have value b.end() after the swap."
>
> For GCC's std::list the past-the-end iterators are not swapped, so
> after the swap `beg' refers to the beginning of `l2' and `end' refers
> past-the-end of `l1', so your loop compares iterators into different
> containers, which is undefined behaviour.
>
> You can verify this with GCC's debug mode, compile with
> -D_GLIBCXX_DEBUG. The program will fail when `beg' is incremented past
> the end, because the condition beg!=end is never true.


I guess ISO/IEC 14882, Second edition, 2003-10-15 is not the correct
reference material in this case.
There is this section 23.1 Container requirements, item 10
"no swap() function invalidates any references, pointers, or iterators
referring to the elements of the
containers being swapped."

I would like to know please, what is the correct C++ ISO number you
are working with.
I guess I will find then the paragraph you quoted very easy.
Thanks.




[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux