mardi 5 juillet 2022

assign pointer to constant pointer in c++

I have a constant pointer cp that points to A and a non constant pointer p that points to B. I wold say that I can assign cp to p, i.e. p=cp because in this way both cp and p point to A and I cannot do the opposite: cp=p, because in this way I am saying that cp should point to B but cp is a constant pointer so I cannot change what it is pointing to. I tried with this simple code but the result is the opposite, can someone explain me what is the correct version please?

std::vector<int> v;
v.push_back(0);
auto cp = v.cbegin(); // .cbegin() is constant 
auto p = v.begin(); // .begin() is non constant 

now if I write cp=p the compiler doesn't mark as error, but if I write p=cp the compiler marks the error.

Aucun commentaire:

Enregistrer un commentaire