如何使用 C++11 移动语义从函数 return std::vector?
How to return std::vector from a function using C++11 move semantics?
我知道 C++11 从这个 link 中获得了移动语义:
Elements of Modern C++ Style
但是它没有介绍如何return一个向量使用移动语义。如何做到这一点?
像这样:
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;
}
return语句的操作数符合复制省略条件,如果没有省略复制,则该操作数被认为是return类型的移动构造函数,所以一切都是尽可能好。
我知道 C++11 从这个 link 中获得了移动语义: Elements of Modern C++ Style
但是它没有介绍如何return一个向量使用移动语义。如何做到这一点?
像这样:
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;
}
return语句的操作数符合复制省略条件,如果没有省略复制,则该操作数被认为是return类型的移动构造函数,所以一切都是尽可能好。