最好的办法,以返回C​​ ++对象的名单? [英] Best way to return list of objects in C++?

查看:190
本文介绍了最好的办法,以返回C​​ ++对象的名单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这已经有一段时间,因为我在C ++编程,并从蟒蛇来了之后,我觉得SOOOO在一条直线夹克,确定我不会夸大其词。

It's been a while since I programmed in C++, and after coming from python, I feel soooo in a straight jacket, ok I'm not gonna rant.

我有几个功能充当管道,接受一个列表作为输入,返回另一个列表作为输出(基于输入),

I have a couple of functions that act as "pipes", accepting a list as input, returning another list as output (based on the input),

这是在概念,但在实践中,我使用的std ::矢量重新present名单,是可以接受的?

this is in concept, but in practice, I'm using std::vector to represent the list, is that acceptable?

进一步,我没有使用任何指针,所以我用的std ::矢量<&SOMETYPE GT; the_list(some_size); 作为变量,直接返回它,即收益the_list;

further more, I'm not using any pointers, so I'm using std::vector<SomeType> the_list(some_size); as the variable, and returning it directly, i.e. return the_list;

P.S。到目前为止,这一切ok,项目规模小,这似乎并没有影响到性能,但我仍然希望得到这方面的一些输入/建议,因为我觉得我用C ++编写Python。

P.S. So far it's all ok, the project size is small and this doesn't seem to affect performance, but I still want to get some input/advice on this, because I feel like I'm writing python in C++.

推荐答案

我能看到的唯一的事情是,你强迫你返回列表的副本。这将是更有效地做一些事情,如:

The only thing I can see is that your forcing a copy of the list you return. It would be more efficient to do something like:

  void DoSomething(const std::vector<SomeType>& in, std::vector<SomeType>& out)
  {
  ...
  // no need to return anything, just modify out
  }

由于你要返回列表通过,您避免额外的副本。

Because you pass in the list you want to return, you avoid the extra copy.

编辑:这是一个古老的答复。如果你可以用一个现代的C ++编译器与移动语义,你不必担心这一点。当然,这个答案仍然适用,如果你正在返回的对象没有移动语义。

This is an old reply. If you can use a modern C++ compiler with move semantics, you don't need to worry about this. Of course, this answer still applies if the object you are returning DOES NOT have move semantics.

这篇关于最好的办法,以返回C​​ ++对象的名单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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