in c++ how do I return an array of objects from a function?
2 Answers
myobject *myfunc()
{
return new myobject[10];
}
But beware - you are transferring ownership of the array to the caller, might be a cause for memory leaks.
EDIT: returning a pointer to an array is a lot faster than returning a std::vector. If you are going to use a std::vector (as others have written), you may prefer to do it like this:
void myfunc(std::vector<myobject> &result)
{
result.resize(0);
for(int i=0;i<10;++i)
result.push_back(myobject());
}
8 Comments
John Dibling
Technically correct. But this ignores the fact that this is horrible code. (edit: maybe it is objects)
Šimon Tóth
@John What is so horrible about this code? What do object have to do with this?
John Dibling
@Let_Me_Be: In reverse order: OP asked specifically about an array of objects. If you've been on SO for more than a few days, it should be clear why this is bad. Leaking memory is not good, and this code is a breeding ground for memory leaks.
Steve Jessop
@GMan: NRVO doesn't help much if the return value from the function isn't used in an initializer, and move semantics in C++0x are about as helpful as the fact that java.lang.Vector can be efficiently returned by garbage-collected reference, if what you're using is only standard C++. I think that C++ is a bit awkward here - all the options have downsides (return vector by value may be very inefficient; passing a vector breaks up expressions; returning a raw allocation is horrible; a template function taking an output iterator must be compiled in). We can't always act as though it isn't.
Doc Brown
Don't blame me for C++ not having a good builtin mechanism for returning references to big data structures.
|