Pergunta

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;
Foi útil?

Solução

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.

Outras dicas

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top