jamesatha
jamesatha

Reputation: 7620

Copying a vector from the stack onto the heap

I have method that takes in a const vector reference. I want to put a mutable version of the vector on the heap and return that

This compiles but I am unsure if it is actually doing what I think. I am not sure if I am getting lucky with the memory here:

vector<Type> *vect = new vector<Type>;
*vect = vectReference;

Upvotes: 3

Views: 1267

Answers (4)

Rost
Rost

Reputation: 9089

It's OK, you made dynamically allocated vector copy. But the same could be done in more short way using copy constructor instead of default constructor and assignment operator:

vector<Type> *vect = new vector<Type>(vectReference);

Also would like to suggest to use smart pointer instead of raw one: std::unique_ptr or std::shared_ptr - depending on your code semantics.

Upvotes: 2

WhozCraig
WhozCraig

Reputation: 66254

This will perform exactly what you want. you can even shorten it by:

vector<Type> *vect = new vector<Type>(vectReference);

to invoke the copy constructor rather than the assignment operator.

Upvotes: 1

Mark
Mark

Reputation: 6093

This code works correctly.

However, you need to ensure that the "vect" allocates space, which should be freed later, so you probably want to use a std::auto_ptr to ensure, that the object is being destroyed:

std::auto_ptr<std::vector<Type> > vect(new std::vector<Type>);
*vect = vectReference;

Upvotes: 1

Aleksey Bakin
Aleksey Bakin

Reputation: 1536

As I understand you, you do it right. On second line you copy vector from vectReference into vect allocated on heap.

Upvotes: 1

Related Questions