How to return a 'read-only' copy of a vector

michael picture michael · Mar 17, 2010 · Viewed 8.1k times · Source

I have a class which has a private attribute vector rectVec;

class A {
private:
   vector<Rect> rectVec;
};

My question is how can I return a 'read-only' copy of my Vector? I am thinking of doing this:

class A {
public:
  const vect<Rect>& getRectVec() { return rectVect; }
}

Is that the right way? I am thinking this can guard against the callee modify the vector(add/delete Rect in vector), what about the Rect inside the vector?

Answer

Peter Alexander picture Peter Alexander · Mar 17, 2010

That is the right way, although you'll probably want to make the function const as well.

class A {
public:
  const vect<Rect>& getRectVec() const { return rectVect; }                           
};

This makes it so that people can call getRectVec using a const A object.