I need to merge some strings to one, and for efficient reason I want to use move semantic in this situation (and of course those strings won't be used any more). So I tried
#include <iostream>
#include <algorithm>
#include <string>
int main()
{
std::string hello("Hello, ");
std::string world("World!");
hello.append(std::move(world));
std::cout << hello << std::endl;
std::cout << world << std::endl;
return 0;
}
I supposed it will output
Hello, World!
## NOTHING ##
But it actually output
Hello, World!
World!
It will result in the same thing if replacing append
by operator+=
. What's the proper way to do that?
I use g++ 4.7.1 on debian 6.10
C doesn't have a direct equivalent to move semantics, but the problems that move semantics solve in c++ are much less common in c: As c also doesn't have copy constructors / assignment operators, copies are by default shallow, whereas in c++ common practice is to implement them as deep copy operations or prevent them ...
Move semantics allows you to avoid unnecessary copies when working with temporary objects that are about to evaporate, and whose resources can safely be taken from that temporary object and used by another.
std::move in C++ Moves the elements in the range [first,last] into the range beginning at result. The value of the elements in the [first,last] is transferred to the elements pointed by result. After the call, the elements in the range [first,last] are left in an unspecified but valid state.
By overloading a function to take a const lvalue reference or an rvalue reference, you can write code that distinguishes between non-modifiable objects (lvalues) and modifiable temporary values (rvalues). You can pass an object to a function that takes an rvalue reference unless the object is marked as const .
You cannot move a string
into part of another string
. That would require the new string
to effectively have two storage buffers: the current one, and the new one. And then it would have to magically make this all contiguous, because C++11 requires std::string
to be in contiguous memory.
In short, you can't.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With