3

as we known, a movable object is one would not be copied deeply when it be assigned to another one of same type. By this way, we can save a lot of time. But today, I found a phenomenon stange to me. Please view code as following.

#include <string>
#include <iostream>
int main() {
std::string s1 = "s1";
std::string s2 = "s2";

std::cout << "  s1[" << ( void* ) &s1[0] << "]:" + s1
    << ", s2[" << ( void* ) &s2[0] << "]:" + s2
    << std::endl;
s1.swap( s2 );
std::cout << "  s1[" << ( void* ) &s1[0] << "]:" + s1
    << ", s2[" << ( void* ) &s2[0] << "]:" + s2
    << std::endl;

s2 = std::move(s1);
std::cout << "  s1[" << ( void* ) &s1[0] << "]:" + s1
    << ", s2[" << ( void* ) &s2[0] << "]:" + s2
    << std::endl;

return EXIT_SUCCESS; }

After moving, although the contents of strings have been changed, but the address that really storing the data of a string has not been changed.

If the memory addesses would not be changed, can we have a reason to confirm that in fact a deeply copy will be performed instead of just only assigen a pointer to target's member?

thanks! Leon

David Haim
  • 25,446
  • 3
  • 44
  • 78
Leon
  • 1,489
  • 1
  • 12
  • 31

1 Answers1

8

a movable object is one would not be copied deeply when it be assigned to another one of same type

Only if it makes sense. in the following snippet

int i0 = 11;
int i1 = std::move(i0);

there will be no "stealing" simply because there is nothing to steal. so the premise of the question is flawed - a move operation would "steal" the content of the movee if it makes sense to do so.

Also note that in the C++ world, unlike Java and C#, an object is everything that occupies memory - integers, pointers, characters - all of them are objects.

std::string uses an optimization technique called "short string optimization" or SSO. If the string is short enough (and "short enough" is implementation defined), no buffer is dynamically allocated and hence nothing to "steal". when such short string is moved, the content of the string is so short it's just copied to the moved-into string without messing with dynamically allocated buffers.

Pavan Manjunath
  • 27,404
  • 12
  • 99
  • 125
David Haim
  • 25,446
  • 3
  • 44
  • 78
  • I tried a few of times with different number of charecters. As you said, when the number of charecters to be moved equals/greats 16, the addresses of both change. If both of two numbers less than 16, it just simplly copys the buffers. Thank you again! Leon – Leon Oct 20 '18 at 09:49