Alex
Alex

Reputation: 1345

Return vector from function without it being destroyed

I have come across an interesting problem. I have a function in C++ that returns a vector filled with classes. Once the vector is returned, it calls deconstructors for each class that is element in the vector.

The problem is an obvious one: the data is destroyed where a class points to the pointers, which get released when the object is destroyed. I can only assume the deconstructors are called because the vector is on the stack, and not on the heap.

So the question is:

Is there anyway to keep returning vector from a function, without it being destroyed? Or would I have to either pass a pointer to return vector as an input to the function?

Upvotes: 6

Views: 20199

Answers (3)

Timmmm
Timmmm

Reputation: 96596

C++ vectors are allocated on the heap. When you return a vector by value a new one will be created with copies of all the elements, then the original elements will be destroyed.

It sounds like you haven't defined your copy constructors properly. For example:

class ThisIsWrong
{
public:
    ThisIsWrong()
    {
        i = new int;
        *i = rand();
    }
    ~ThisIsWrong()
    {
        delete i;
        i = nullptr;
    }

    int value() const
    {
        return *i;
    }

private:
    int* i;
};

void foo()
{
    vector<ThisIsWrong> wronglets;
    wronglets.push_back(ThisIsWrong());
    return wronglets;
}

void main()
{
    vector<ThisIsWrong> w = foo();
    w[0].value(); // SEGFAULT!!
}

You either need to delete the copy and assignment constructors (which will then turn this into a compilation error instead of runtime), or implement them properly.

Upvotes: 0

Sarmad
Sarmad

Reputation: 11

C++11 should solve your problem using rvalue references. Honestly, I haven't tried it myself, but from what I read it will do exactly what you are trying to do, return the vector without destroying and recreating it (by passing the memory allocated by that vector on to the new vector instead of having the new vector create its own memory and copy the contents over from the old one).

Upvotes: 1

Vlad
Vlad

Reputation: 35594

You can create anything on heap with new. You shouldn't give out from the function the references to your stack objects, as they will be destroyed as soon as the function finishes.

If you prefer your function to return the vector by value, be sure that the objects inside the vector implement copy constructor (and perhaps assignment operator, too, not sure about that). Having that, please do not forget about the Rule of Three.

Upvotes: 4

Related Questions