Consider this:
struct Foo {
std::vector<double> x;
mutable double* xp;
void foo () const { xp = &(x[0]); }
};
This wont compile with because of
error: invalid conversion from 'const double*' to 'double*' [-fpermissive]
The fix is rather simple:
struct Foo {
mutable std::vector<double> x;
mutable double* xp;
void foo () const { xp = &(x[0]); }
};
But what if I do not want to make the vector mutable? What is the best way to get a pointer to non-const from a const vector in this case?
The problem I am trying to solve is the following:
I have some code that looks like this (sorry cant post a complete code):
struct Foo {
mutable DataSource data;
void load(int index) const { data->GetEntry(index); }
void getX() const { return data->element->x; }
};
Where DataSource
I cannot change and its GetEntry
reads from a file to update its element
. Reading from the file in this way is rather slow, thus I would like to change it to
struct Foo {
mutable DataSource data;
std::vector<DataSource::Element> elements;
DataSource::Element* current;
void loadAll() { /*... read all elements into the vector ...*/ }
void load(int index) const { current = &(elements[index]); }
void getX() const { return current->x; }
};
because that is what I can do without breaking (lots of) existing code. I could drop the constness at all which would be maybe a better design, but if possible I want to avoid that, because then I have to fix things in other places.