C ++:在字符串#append中移动语义

时间:2012-10-31 03:00:30

标签: c++ c++11 move-semantics

我需要将一些字符串合并为一个,并且出于有效的原因,我想在这种情况下使用移动语义(当然这些字符串将不再被使用)。所以我试过

#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;
}

我猜它会输出

Hello, World!
## NOTHING ##

但实际输出

Hello, World!
World!

如果将append替换为operator+=,则会产生相同的结果。这样做的正确方法是什么?

我在debian 6.10上使用g ++ 4.7.1

1 个答案:

答案 0 :(得分:8)

您无法将string移动到另一个string部分。这将要求新的string有效地拥有两个存储缓冲区:当前的缓冲区和新的缓冲区。然后它必须神奇地使这一切都连续,因为C ++ 11要求std::string连续的内存中。

简而言之,你不能。