Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Move semantic in string#append

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

like image 344
neuront Avatar asked Oct 31 '12 03:10

neuront


People also ask

Does C have move semantics?

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 ...

What is a move semantic?

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.

What does move() do in c++?

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.

How to use rvalue reference?

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 .


1 Answers

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.

like image 86
Nicol Bolas Avatar answered Sep 30 '22 02:09

Nicol Bolas