Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to return list of objects in C++?

Tags:

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),

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

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. 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++.

like image 806
hasen Avatar asked Feb 05 '09 07:02

hasen


1 Answers

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.

Edit: 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.

like image 118
BigSandwich Avatar answered Oct 20 '22 04:10

BigSandwich