C++ 如何使用C+从函数返回std::vector+;11移动语义?

C++ 如何使用C+从函数返回std::vector+;11移动语义?,c++,c++11,move-semantics,copy-elision,C++,C++11,Move Semantics,Copy Elision,我知道C++11具有此链接中的移动语义: 但它没有介绍如何使用移动语义返回向量。如何做到这一点?像这样: std::vector<std::string> make_a_vector_of_strings() { std::vector<std::string> result; // just an example; real logic goes here result.push_back("Hello"); result.push_

我知道C++11具有此链接中的移动语义:

但它没有介绍如何使用移动语义返回向量。如何做到这一点?

像这样:

std::vector<std::string> make_a_vector_of_strings()
{
    std::vector<std::string> result;

    // just an example; real logic goes here
    result.push_back("Hello");
    result.push_back("World");

    return result;
}
std::vector make_a_vector_of_string()
{
std::向量结果;
//这只是一个例子,真正的逻辑在这里
结果:推回(“你好”);
结果:推回(“世界”);
返回结果;
}

return语句的操作数符合复制省略的条件,如果没有省略复制,则该操作数将被视为返回类型的移动构造函数,因此一切尽可能好。

我看到一些帖子说使用std::vector&&as返回类型或返回移动(result)。所有这些让我困惑@DeanChen:这两个想法听起来完全错误。我认为你应该限定
result
只在return语句中移动,因为它是一个局部变量/参数。如果
result
是数据成员(或全局,eww),它将不会被移动。@dyp:如果
result
不是局部变量,代码仍然会做正确的事情,因为那样它会被别名化,我们不希望在没有明确请求的情况下秘密地变异别名值。的确,但我担心您的答案可能会被误解:有人可能会认为返回语句总是移动其操作数。