I know this sounds like a strange question, but bear with me.
I have a custom class that has some large objects which need to be returned by reference to avoid a copy.
My class looks something like this:
class csv_File {
public:
csv_File(std::string); //constructor
std::string const& access(int,int) const;
void modify_element(int column,int row ,std::string value) {
storage.at(row).at(column)=value;
}
private:
mutable std::vector < std::vector<std::string> > storage;
};
The code for access is:
string const& csv_File::access(int column,int row) const {
return storage.at(row).at(column);
}
When I try to compile this, I get an error, as it wants
csv_File::modify_element(int column,int row ,std::string value) const {}
In practice, storage is logically const, but I just need to be able to modify it once in a while. Is there a way to do this?
Also, a related question. If I call modify_element to modify an element in storage, but previously, I have returned a reference to that element using access, will the reference that was returned previously pick up the new value after the modify_element call?
After fixing up your program, and with the hint from @user763305, I suppose you have something like this (note: this program compiles, but invokes undefined behavior when run, since the
storagevector is left empty):and you get an error like this:
So, you have a
constobject and are trying to invokemodify_elementon it. Logically, this is a mistake — you can’t modifyconstobjects!You have, as I see it, two choices for a fix. Either you can declare the
vectorobjectmutableand themodify_elementmethodconst, or you can modify your object factory to return non-const references.Solution 1:
Solution 2:
EDIT
And, yes, if you previously returned a reference to a
stringin yourvector, and you subsequently assign a new value to thatstringas you do inmodify_element, then the previous reference will reflect the new value.Note that the previous reference will be invalid if you destroy the vector, erase that
vectorelement, or do anything to cause thevectorto grow beyond its previous capacity.