How to use operator = to copy a vector of pointers?
The operador =
is already set to vector<int*>
Is it necessary to reserve memory before doing so?
No. Memory allocation by std::vector
is automatic. Do not confuse memory for pointers with memory for integers to which pointers point to. I mean, if you copy one vector from pointers to another, both will point to the same integers.
What's the difference between making a builder per copy and implementing the assignment operator? Builder by copy only makes a copy of the object, while the assignment operator changes the content (in this case)?
They are different things. One is constructor and generates a new object; Another is an operator that operates on an existing object.
Generally, it is expected that when an object is created as a copy of another the result will be equal objects. That is, after we create B
of the form Objeto B(A)
, we expect that B==A
Generally, it is expected that when one object is assigned to another, the result is equal objects. That is, after we apply B=A
, we expect that B==A
Notice that you usually expect the same result through both operations, but they are different things and you can implement each as you like.
I hope the example below is instructive, realize that I do not create either the assignment operator or the constructor. I let the compiler manage them automatically:
class ints
{
public:
//vetor de ponteiros para int
std::vector<int*> inteiros;
//função que imprime valor de todos inteiros apontados
void escreve()
{
for(auto i:inteiros)
std::cout << *i << ", ";
std::cout << std::endl;
}
};
Creating an object ints A
and saving in the vector this a few pointers:
//declara 3 ints
int x = 1;
int y = 2;
int z = 3;
//cria objeto A da classe ints
ints A;
//salva ponteiros em A
A.inteiros.push_back(&x);
A.inteiros.push_back(&y);
A.inteiros.push_back(&z);
Creating an object by copying A
:
//cria objeto B através de cópia
ints B(A);
Creating an object and using assignment to match it with A
:
//cria objeto C e usa operador atribuição
ints C;
C = A;
When the content is printed, it is checked that objects point to the same x
, y
and z
integers declared initially:
//verifica conteúdo
A.escreve();
B.escreve();
C.escreve();
(result in terminal)
1, 2, 3,
1, 2, 3,
1, 2, 3,
All objects contain vectors that point to the same integers, that is, the value of the pointers saved in the vectors were all copied from A
. You can check this by changing the value of any of the named integers:
//A, B e C apontam para os mesmos inteiros, incluindo y
y = 666;
//verifica-se que a mudança é visível através de todos objetos:
A.escreve();
B.escreve();
C.escreve();
(result in terminal)
1, 666, 3,
1, 666, 3,
1, 666, 3,
Here is the example above online.