I am interested in creating a class I can use like
class MyClass {
vector<int> m_vec;
public:
// Either this
const& vector<int> vec;
// Or some version of this.
const& vector<int> getVec() { return m_vec } ;
MyClass() : vec(m_vec) {}
void changeVec() { m_vec.push_back(5); }
}
Now if I want to use getVec(), the syntax is a little cumbersome:
myClass.getVec()[5]
I would much prefer to be able to either somehow use
myClass.vec[5]
without exposing the ability to modify the vector. IE, I want the member variable to be private, but for a const-version of the variable to be public without a syntactical or performance overhead.
If I add the const& vector reference, the compiler (at least my version of GCC) actually makes the class take more memory. So
Just to be clear, this is an example -- in the real case, the usage is a bit more compelling than in the vector case. Also, the memory usage is important as lots of these objects exist and will be copied, so this is not premature optimization. At this point, I'm using the getVec()[0] approach, but the ugliness is killing me.
If, for some reason, MyClass::operator[]
is not suitable, just make a tiny wrapper class for your vector.
struct Wrapper {
friend class MyClass;
int operator[](size_t s) const { return vec[s]; }
private:
vector<int> vec;
};
class MyClass {
public:
Wrapper vec;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With