Returning a Private Vector

I have a class with a private attribute that is a vector. What's the best way to do a getter function?

  • Returns the entire vector: vector<char*> getNames() { return names; }

    • Will this return a copy or a pointer? Will it be available from his private?
  • Return an iterator: vector<char*>::iterator getNames() { return names.begin(); }

  • Make the vector public
    • I know this is bad OOP practice just listing the options.
+3


source to share


2 answers


Return const vector<char*>&

. It guarantees that it will not be modified externally and will not make a copy.



+7


source


If you're actually using vector<char *>

internally, the only way to ensure that the user doesn't change names (without the ugly and obvious one const_cast

) is to return value vector<const char *>

by value:

vector<const char *> getNames() const { return {names.begin(), names.end()}; }

      

or, pre-C ++ 11:



vector<const char *> getNames() const { return vector<const char *>(names.begin(), names.end()); }

      

Returning vector<char *>

, either by value or by const reference, will prevent the user from modifying your vector itself, but not the contents of the strings it points to.

Much better to use vector<std::string>

, in which case you can simply return a const reference.

+2


source







All Articles