views:

176

answers:

3

Hi

I'm trying to swap two std::list< 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 :/

+3  A: 

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).

Mark B
+4  A: 

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.

sbi
A: 

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

Jay
Pardon me French, but that's BS. Copying uses copy constructors (and `std::swap()` is well defined for all types supporting copy construction).
sbi