C :在字符串#附录中移动语义

C++: Move semantic in string#append

本文关键字:移动 语义 字符串      更新时间:2023-10-16

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

#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!

如果用operator+=替换append,它将导致同一件事。做什么的正确方法是什么?

我在Debian 6.10

上使用G 4.7.1

您不能将string移至另一个string part 中。这将要求新的string有效地具有两个存储缓冲区:当前的缓冲区和新的存储缓冲区。然后它必须神奇地使所有连续,因为C 11需要std::string连续内存中。

简而言之,您不能。