Pages: Welcome | Projects

String move, insights

2017/3/9
Tags: [ C & C++ ] [ Hacking ]

The easiest way of implementing a string move semantics is simply to steal the internal byte representation pointer of the other element, and put an empty one in its place.

This is just intuition, but I was curious to check it myself. Stupid snippet to check this out:

  #include <iostream>
  #include <string>
  int main()
  {
      std::string s1 = "hello";
      std::cerr << "1 " << s1 << " -> " << (void*)s1.c_str() << std::endl;
      std::string s2 = std::move(s1);
      std::cerr << "1 " << s1 << " -> " << (void*)s1.c_str() << std::endl;
      std::cerr << "2 " << s2 << " -> " << (void*)s2.c_str() << std::endl;
  }

The surprising result:

1 hello -> 0x7ffce8e6a790
1  -> 0x7ffce8e6a790
2 hello -> 0x7ffce8e6a770

Not exactly what I thought… a new string really. Could it be because "hello" is so short?

#include <iostream>
#include <string>
int main()
{
    std::string s1 = "hello world of people long long";
    std::cerr << "1 " << s1 << " -> " << (void*)s1.c_str() << std::endl;
    std::string s2 = std::move(s1);
    std::cerr << "1 " << s1 << " -> " << (void*)s1.c_str() << std::endl;
    std::cerr << "2 " << s2 << " -> " << (void*)s2.c_str() << std::endl;
}

How about this long string now?

1 hello world of people long long -> 0xebec20
1  -> 0x7ffd740008e0
2 hello world of people long long -> 0xebec20

Interesting :)