4

The cppreference page says about std::basic_string::swap that it has constant complexity. As I assume that means that copying contents cannot happen, only the swapping of pointers, or similar. I wrote a test code and experienced that it does move contents under VS2010. Test code:

std::string s1("almafa");
std::string s2("kortefa");
std::cout << "s1.c_str(): "<< (void*)s1.c_str() << std::endl;
std::cout << "s2.c_str(): "<< (void*)s2.c_str() << std::endl;
std::cout << "SWAP!" << std::endl;
s1.swap(s2);
std::cout << "s1.c_str(): "<< (void*)s1.c_str() << std::endl;
std::cout << "s2.c_str(): "<< (void*)s2.c_str() << std::endl;

Output on g++ 4.6.3

s1.c_str(): 0x22fe028
s2.c_str(): 0x22fe058
SWAP!
s1.c_str(): 0x22fe058
s2.c_str(): 0x22fe028

Output on VS2010

s1.c_str(): 000000000022E2D0
s2.c_str(): 000000000022E320
SWAP!
s1.c_str(): 000000000022E2D0
s2.c_str(): 000000000022E320

Is it a divergency from the standard or something is happening that I have no knowledge about?

Notinlist
  • 16,144
  • 10
  • 57
  • 99

1 Answers1

5

Some implementation of std::string use the short string optimization:

From How is std::string implemented?:

a "short string optimization" (SSO) implementation. In this variant, the object contains the usual pointer to data, length, size of the dynamically allocated buffer, etc. But if the string is short enough, it will use that area to hold the string instead of dynamically allocating a buffer.

So the swap in your case does a copy but of fixed size, so O(1).

Community
  • 1
  • 1
Jarod42
  • 203,559
  • 14
  • 181
  • 302