开发者

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

in c++ how do I return 开发者_运维知识库an array of objects from a function?


By returning a std::vector.


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());
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜