Question

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;
Was it helpful?

Solution

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.

OTHER TIPS

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

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;

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top