在C ++中,从函数返回向量仍然是不好的做法吗? [英] In C++, is it still bad practice to return a vector from a function?

查看:416
本文介绍了在C ++中,从函数返回向量仍然是不好的做法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

短版本:在许多编程语言中返回大对象(如向量/数组)是很常见的。如果类有一个移动构造函数,或者C ++程序员认为它是奇怪的/丑陋/憎恶,这种风格现在在C ++ 0x中是否可以接受?



在C ++ 0x中,这是否仍被认为是错误的形式?

  std :: vector< std :: string> ; BuildLargeVector(); 
...
std :: vector< std :: string> v = BuildLargeVector();

传统版本将如下所示:

  void BuildLargeVector(std :: vector< std :: string>& result); 
...
std :: vector< std :: string> v;
BuildLargeVector(v);

在较新版本中, BuildLargeVector 是一个右值,所以使用 std :: vector 的move构造函数构造v,假设(N)RVO不发生。



即使在C ++ 0x之前,由于(N)RVO,第一种形式通常是有效的。然而,(N)RVO由编译器决定。



编辑:问题是真的不在于优化。所示的两种形式在现实世界程序中具有几乎相同的性能。而在过去,第一种形式可能具有数量级的更差的性能。因此,第一种形式是C ++编程中很长一段时间的主要代码气味。 Dave Abrahams对 archive.org/web/20130930101140/http://cpp-next.com/archive/2009/08/want-speed-pass-by-valuerel =nofollow noreferrer>传递/返回值的速度< a>。



简短的答案,如果你需要返回一个值然后返回一个值。不要使用输出引用,因为编译器无论如何。当然有注意事项,所以你应该阅读这篇文章。


Short version: It's common to return large objects—such as vectors/arrays—in many programming languages. Is this style now acceptable in C++0x if the class has a move constructor, or do C++ programmers consider it weird/ugly/abomination?

Long version: In C++0x is this still considered bad form?

std::vector<std::string> BuildLargeVector();
...
std::vector<std::string> v = BuildLargeVector();

The traditional version would look like this:

void BuildLargeVector(std::vector<std::string>& result);
...
std::vector<std::string> v;
BuildLargeVector(v);

In the newer version, the value returned from BuildLargeVector is an rvalue, so v would be constructed using the move constructor of std::vector, assuming (N)RVO doesn't take place.

Even prior to C++0x the first form would often be "efficient" because of (N)RVO. However, (N)RVO is at the discretion of the compiler. Now that we have rvalue references it is guaranteed that no deep copy will take place.

Edit: Question is really not about optimization. Both forms shown have near-identical performance in real-world programs. Whereas, in the past, the first form could have had order-of-magnitude worse performance. As a result the first form was a major code smell in C++ programming for a long time. Not anymore, I hope?

解决方案

Dave Abrahams has a pretty comprehensive analysis of the speed of passing/returning values.

Short answer, if you need to return a value then return a value. Don't use output references because the compiler does it anyway. Of course there are caveats, so you should read that article.

这篇关于在C ++中,从函数返回向量仍然是不好的做法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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