3

I just came across a piece of code written by my ex-colleague few years ago. Honestly, I'm not an C++ expert, so I am seeking help.

The code looks like this:

std::vector<OBJ> objects;

void initobjs()
{
    for (int i=0; i<10; i++)
    {
        OBJ obj;
        obj.type=i;
        obj.len=16;

        objects.push_back(obj);
    }
}

My question is: after function initobjs() returns, aren't all obj instances already out of scope and automatically freed by the C++ runtime system? If they are, will any reference to contents of any of the objects added to the vector cause memory fault or unexpected result?

GManNickG
  • 478,574
  • 51
  • 478
  • 539
cow
  • 1,030
  • 1
  • 11
  • 18

3 Answers3

13

Your concern can be made even more local: obj ends at the bottom of the for-loop.

That said, a container makes a copy of its argument*, and does not store any reference or pointer to the "original" value.

*Hence all containers require their elements be copy-constructible and copy-assignable.

GManNickG
  • 478,574
  • 51
  • 478
  • 539
7

The original objects will be out of scope, but the push_back() method actually creates copies of them, because they are passed by value. So when the initobjs() function exits, the copies are still in the vector; they will be deallocated when you remove them from the vector, or when the vector itself goes out of scope.

If the vector were a vector<OBJ*>, then that would be a different matter altogether: it would mean that you'd have to manually delete every obj the moment you remove it from the vector (unless you store it elsewhere).

Note that C++ does not have any memory management built in at all, except stack-allocated variables, which are deallocated when their scope ends. RAII is the buzz-word you're looking for in case you want to enlighten yourself a bit more.

tdammers
  • 19,940
  • 1
  • 35
  • 54
1

The objects vector will contain "copies" of the OBJ in the for loop. Depending on what the copy constructor of OBJ does this might yield the appropriate results or not.

I would go and check the copy constructor of OBJ for suspicious things.

jdehaan
  • 19,426
  • 6
  • 56
  • 95