按值返回std :: vector [英] Returning std::vector by value

查看:134
本文介绍了按值返回std :: vector的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

经常说在C ++ 11中按值返回std::vector是理智的.

It is often said that in C++11 it is sane to return std::vector by value.

在C ++ 03中,大多数情况都是这样,因为RVO应该优化副本.但这应该会吓跑大多数开发人员.

In C++03 this was mostly true as RVO should optimize away the copy. But that should scared most developers away.

  • 在C ++ 11中,是否总是会移动返回的std::vector局部变量?
  • 如果该向量是局部变量的成员而不是局部变量本身怎么办?
  • 显然不会返回全局变量.还有什么其他情况将不被移走?
  • In C++11 will a returned std::vector local variable always be moved?
  • What if that vector is a member of a local variable instead of a local variable itself?
  • Obviously returning a global variable will not be moved. What other cases will it not be moved?

推荐答案

首先,每次以前可以删除副本,现在仍然可以删除副本,并且在相同情况下也可以删除移动.在本文的其余部分中,我将假定省略由于某种原因而没有发生(假装编译器编写者在某种程度上是懒惰的).

First, every time a copy could be elided before, it can still be elided now, and moves can be elided in the same situations. For the rest of this post I'll assume that elision doesn't happen for some reason (pretend the compiler writer was lazy in a bad way).

在C ++ 11中,是否总是会移动返回的std :: vector局部变量?

In C++11 will a returned std::vector local variable always be moved?

每次都满足复制删除标准,或者显式变量是std::move d.

Every time the criteria for copy elision are met, or the variable is explicitly std::moved.

如果该向量是局部变量的成员而不是局部变量本身怎么办?

What if that vector is a member of a local variable instead of a local variable itself?

除非明确地std::move d,否则它将不会移动.

It won't be moved unless explicitly std::moved.

显然返回的全局变量将不会被移动.还有什么其他情况不会移走?

Obviously returning a global variable will not be moved. What other cases will it not be moved?

每次不满足复制删除标准,并且变量未明确显示std::move d.

Every time the criteria for copy elision are not met and the variable is not explicitly std::moved.

这些都不是不按值返回的有效理由.按值返回是可以的,因为即使没有自动移动该值,也可以使用std::move强制它.

None of those is a valid reason to not to return by value. Return by value is ok, because even when the value is not automatically moved you can force it with std::move.

这篇关于按值返回std :: vector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆