My understanding of const references to a class was that we cannot modify the state of the class i.e. cannot perform any action that modifies any of it's member variables. But consider the following code.
#include <iostream>
#include <vector>
struct Vec {
Vec(std::vector<int>& v) : vec(v) {}
Vec(const Vec& v) : vec(v.vec) {
v.vec.resize(100);
}
std::vector<int>& vec;
};
int main() {
std::vector<int> x;
Vec v1(x);
Vec v2(v1);
v1.vec.resize(10, 0);
v2.vec[5] = 8;
std::cout << v1.vec[5] << std::endl;
return 0;
}
I compiled this code using g++:4.8.3 with -Wall flag and it compiled. I have two questions.
- In
Veccopy construtor, we pass a const reference to aVec v. By extension of constness ofv,v.vecshould also have been aconst std::vector<int>&. Then how does it get copied to typestd::vector<int>? - The only logical way the above can happen is if constness of a class doesn't apply to it's member variable. So my question is what implications does a constness of a class has on it's member variables ?
Aucun commentaire:
Enregistrer un commentaire