1

in c++ how do I return an array of objects from a function?

1
  • 1
    What does your book say? Commented Nov 9, 2010 at 21:54

2 Answers 2

20

By returning a std::vector.

Sign up to request clarification or add additional context in comments.

Comments

6
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

Technically correct. But this ignores the fact that this is horrible code. (edit: maybe it is objects)
@John What is so horrible about this code? What do object have to do with this?
@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.
@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.
Don't blame me for C++ not having a good builtin mechanism for returning references to big data structures.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.