2

I had a whole pile of trouble with objects getting destroyed(and their heap data along with them) when returning vectors from functions a while back. I don't remember the exact details so I tried returning a vector of objects today and their destructor didn't get triggered.

Do I remember it wrong? If i made a vector like this:

std::vector<myObject> MakeVectorOfMyObjects(int size) {
    std::vector<myObject> ret;
    for (int i = 0; i < size; i++) {
        ret.push_back(myObject());
    }
    return ret;
}

and called it like that:

std::vector<myObject> stuff = MakeVectorOfMyObjects(5);

Is it guaranteed that the the vector that now resides in "stuff" is the exact same as the one i built in the function without any of the objects getting destroyed, remade or otherwise manipulated during the return and assignment?

Also does it make any difference whether I pass a vector to a function by reference or by value?

EDIT: getting a bit vague answers so let me rephrase: How to I guarantee that the the vector in "stuff" is the same pile of bits as the one I created in the function? (outside creating the vector with new keyword and returning the pointer that is)

user81993
  • 6,167
  • 6
  • 32
  • 64
  • You're pretty much guaranteed that in this case. Compilers are good at that optimization. In C++11, it falls back to moving the vector out instead of copying it. – chris Feb 24 '15 at 18:53
  • 5
    More the likely the compiler used [RVO](http://en.wikipedia.org/wiki/Return_value_optimization) or [Move Semantics](http://stackoverflow.com/questions/3106110/what-is-move-semantics) if you are using C++11 – NathanOliver Feb 24 '15 at 18:55

2 Answers2

0

Is it guaranteed that the the vector that now resides in "stuff" is the exact same as the one i built in the function without any of the objects getting destroyed, remade or otherwise manipulated during the return and assignment?

No. But it CAN be. This is due to optional return value optimization. Well-written code must work in either case.

Also does it make any difference whether I pass a vector to a function by reference or by value?

Yes. The rules for passing a vector by reference or value are the same as for any class.

Neil Kirk
  • 21,327
  • 9
  • 53
  • 91
0

When you returning local vector "ret" object from function it'll be copied (or moved in case of C++11) into the local object "stuff".

You shouldn't do anything special for it, this is how works "returning by value" mechanism.

ars
  • 707
  • 4
  • 14