Recently I've stumbled upon a bit of an impasse. Usually, people tend to recommend the use of accessors and mutators for classes because they provide data encapsulation or hiding. This is all good and well for my Foo class here:
Code: Select all
class Foo
{
private:
int SomeVar;
public:
int GetSomeVar() const { return SomeVar; }
void SetSomeVar(int val) { SomeVar = val; }
};
Code: Select all
class Bar
{
private:
std::vector<int> SomeVector;
public:
const std::vector<int>& GetSomeVector() const { return SomeVector; }
void SetSomeVector(const std::vector<int>& vec) { SomeVector = vec; }
};
- The mutator/accessor combination seems very inefficient, since modifying the vector requires a complete copy from the getter, for it to be copied again after it was modified when the setter is called.
- The use of accessors/mutators is usually recommended, but somehow using them doesn't seem to make sense here since the mutators/accessors do nothing more than modify the internal variable. My point: why not just lend the user global access altogether?
Code: Select all
for(int i(0); i < BarObj.GetSomeVector().size(); ++i)
{
BarObj.GetSomeVector()[i] ...
}
Code: Select all
const std::vector<int>& vec = BarObj.GetSomeVector();
for(int i(0); i < vec.size(); ++i)
{
vec[i] ...
}