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

c++, const-correctness

Solution

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.

Problem

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?

Original source