开发者

std::swap returns 0xBAADF00D

开发者 https://www.devze.com 2023-01-08 21:42 出处:网络
I\'m trying to swap two std::list&开发者_StackOverflow中文版lt; dontcare* >::iterators under Visual 2005.

I'm trying to swap two std::list&开发者_StackOverflow中文版lt; dontcare* >::iterators under Visual 2005.

Iter it1 = ... ,it2 = ...; // it1 and it2 are ok, not end() or such
if(...){
    std::swap(it1,it2);
}

The swap works, but when I leave the if() scope, it1 points to 0xbaadfood. It2 is ok though.I tried several variations, including swap_iter and a hand-made swap.

Any help appreciated :)

EDIT

Ok, so shame time.

The swapped it1 was a local variable in the if's scope.

F**king cut'n pasting. Sorry for wasting your time :/


This following program

#include <iostream>
#include <vector>
#include <algorithm>

int main(){
    std::vector<int> v;
    for(std::vector<int>::size_type idx=0; idx<10; ++idx)
        v.push_back(static_cast<int>(idx));

    std::vector<int>::iterator it1 = v.begin();
    std::vector<int>::iterator it2 = v.begin() + v.size()/2;

    std::cout << static_cast<void*>(&*it1) << ':'  << *it1
              << ' ' << static_cast<void*>(&*it2) << ':'  << *it2 << '\n';
    std::swap(it1,it2);
    std::cout << static_cast<void*>(&*it1) << ':'  << *it1
               << ' ' << static_cast<void*>(&*it2) << ':'  << *it2 << '\n';

    return 0;
}

compiles, runs, and, as expected, prints

00032A28:0 00032A3C:5
00032A3C:5 00032A28:0

for me.

If it does something else for you, either your compiler or your standard library is broken.

If it does the same for you, then the error is somewhere in the difference between your code and my code. Where, we can't know, because we don't know your code.


Are you omitting code inside your if? Most likely something else within your if check, but after the swap is actually invalidating the iterator (perhaps an erase).


A WAG but perhaps swap is constructing new objects and copying them (and the copy is not valid because it uses the default constructor)?

0

精彩评论

暂无评论...
验证码 换一张
取 消