Returning std::vector with std::move(用 std::move 返回 std::vector)
问题描述
我有一个非常基本的问题:使用 std::move 返回 std::vector<A> 是个好主意吗?例如:
I have a very basic question: is it a good idea to return a std::vector<A> using std::move? For, example:
class A {};
std::vector<A> && func() {
std::vector<A> v;
/* fill v */
return std::move(v);
}
我应该以这种方式返回std::map、std::list..等吗?
Should I return std::map, std::list.. etc... in this way?
推荐答案
你声明一个函数通过 r-value 引用返回 - 这几乎不应该这样做(如果你通过引用返回本地对象,你最终会得到悬垂的参考).而是将函数声明为按值返回.这样,调用者的值将由函数返回的 r 值构造.返回的值也将绑定到任何引用.
You declare a function to return by r-value reference - this should almost never be done (if you return the local object by reference, you will end up with a dangling reference). Instead declare the function to return by value. This way the caller's value will be move constructed by the r-value returned by the function. The returned value will also bind to any reference.
其次,不,您应该不使用显式 std::move 返回,因为这会阻止编译器使用 RVO.没有必要,因为编译器会自动将返回的任何左值引用转换为右值引用.
Secondly, no, you should not return using an explicit std::move as this will prevent the compiler to use RVO. There's no need as the compiler will automatically convert any l-value reference returned to an r-value reference if possible.
std::vector<A> func() {
std::vector<A> v;
/* fill v */
return v; // 'v' is converted to r-value and return value is move constructed.
}
更多信息:
- 在从函数返回值时使用 std::move() 以避免复制
- RValue 引用 (&&) 的返回是否有用?
这篇关于用 std::move 返回 std::vector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:用 std::move 返回 std::vector
基础教程推荐
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- CString 到 char* 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
