Hi,
I am designing a class that has a vector as a private member. My class also has a member function that returns the vector. I am trying to decide if this function should return a copy of the private vector or a reference to it:
I would like to allow users to iterate thru the vector using numbers2().begin() and numbers2().end() directly (Note that this wouldn't work using number1 since both expressions return a different copy of the vector). But I've heard that I should avoid returning handles to object internals because of possible dangling handlers. I would like to know the thoughts of this group.Code:#include <vector> using namespace std; class A { public: vector<int> numbers1() { return _numbers; } vector<int>& numbers2() { return _numbers; } private: vector<int> _numbers; };
Thank you.




Reply With Quote