Scholar
Scholar

Reputation: 293

Can you dynamically allocate a vector?

I need my vector container to persist past the end of the function that allocates it.

void initVector() {
    vector<obj1*> R;
}

Why is this not valid?

void initVector() {
    vector<obj1*> R = new vector<obj1*>;
}

Upvotes: 0

Views: 109

Answers (1)

Pradhan
Pradhan

Reputation: 16777

It should be vector<obj1*>* R = new vector<obj1*>;. However, with C++11's move semantics, using pointers or references to avoid expensive copies is usually not needed. In the case of a vector, the below code doesn't copy tempVec - it will move it at least. More likely that compiler will elide the copy. You can read more about it here.

vector<obj1*> getVector()
{
 vector<obj1*> tempVec;
 //populate tempVec;
 return tempVec;//The standard guarantees a move at least. Compilers are free to elide this copy.
}

EDIT : As @juanchopanza points out in the comments, if you have a good reason to be doing this, be wary of managing the lifetime of the vector allocated on the heap, R. This isn't an issue specific to this statement - it applies to dynamically allocated structures in general. However, it might need special mention here since you have a vector of pointers. In addition to correctly managing the lifetime of R, you also need to carefully manage the lifetimes of the obj1* it contains. Objects allocated on the heap don't get deleted when the pointer holding them goes out of scope. You will have to manually call delete on a pointer to that memory location when you are done using it. This applies both to the vector* R and, unless owned by some other part of your program, to the obj* that it contains.

Upvotes: 7

Related Questions