neuront
neuront

Reputation: 9622

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

Upvotes: 7

Views: 2487

Answers (1)

Nicol Bolas
Nicol Bolas

Reputation: 474126

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.

Upvotes: 13

Related Questions