tags:

views:

101

answers:

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?

+12  A: 

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.

GMan
Tomaka17
How `OBJ`'s copy constructor behaves could dramatically alter the postconditions of this for loop.
fbrereto
thank you for the prompt answer!!
cow
+7  A: 

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
thanks for answering my question!!
cow
+1  A: 

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
thanks for the answer!!
cow