Visual C++ 2008 Fix of Containers Swap Bug

The C++ standard, specifies in the paragraph 23.1.10 that swapping two containers should not invalidate any references, pointers or iterators refering to the elements of the containers being swapped. Unfortunatelly, that is not the case of the VC++ 2005 implementation.

Imagine the following case:

std::vector vec1;
vec1.push_back(1);
vec1.push_back(2);
vec1.push_back(3);

std::vector vec2;
vec2.push_back(10);
vec2.push_back(20);

std::vector::iterator it1 = vec1.begin();
std::vector::iterator it2 = vec2.begin();

std::cout << *it1 << std::endl;
std::cout << *it2 << std::endl;

You can swap the containers, and still should be able to use the iterators:

vec1.swap(vec2);

std::cout << *it1 << std::endl;
std::cout << *it2 << std::endl;

That works fine in a debug build, but in a release build, the code will crash, because parent pointers added to the iterators because _SECURE_SCL is defined (default for a release build), are broken by the swapping. Stephan Lavavej recently blogged in the VC++ blog about the problem and how it was fixed in Visual Studio 2008. The fix came with a downside in performace, so if your code could be affected by it, make sure you read his comments on the issue.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.