lundi 5 octobre 2015

Copying member variable through const reference to a class

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.

  1. In Vec copy construtor, we pass a const reference to a Vec v. By extension of constness of v, v.vec should also have been a const std::vector<int>&. Then how does it get copied to type std::vector<int> ?
  2. 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