Returning stl containers from functions
I usually use method 4 (almost identical to method 2):
void fill(ItemContainer& result) {
// fill the 'result'
}
ItemContainer a;
fill(a);
None: if you just want to fill std::list
with items, then you can use std::fill
or std::fill_n
or a combination of standard library functions.
It's not clear how exactly you want to fill your list, so I can't comment on your code precisely. If possible, use the standard library. If you cannot, then go for Method 1, and the compiler may optimize away the return value in your code eliding the unnecessary copies, as most compilers implement RVO.
See these articles on copy elision and return value optimization (RVO):
- Copy elision – Wikipedia
- Copy elision – cppreference
Related questions:
- In C++, is it still bad practice to return a vector from a function?
- Returning a c++ std::vector without a copy?
An article by Dave Abrahams:
- Want Speed? Pass by Value
I would still emphasize this: have you seen all the generic functions provided by <algorithm>
header? If not, then I would suggest you to first look into them and see if any of them (or a combination of them) can do what you want to do in your code.
If you want to create and fill the list, then you can use std::generate()
or std::generate_n
function.