Having this:
#include <iostream>
#include <vector>
class A{
std::vector<std::string> vec;
public:
std::string &save(std::string const&s){
vec.push_back(s);
return vec.back();
}
std::vector<std::string> const& getVec() const {
return vec;
}
};
int main(){
A a;
std::string str = a.save("abc");
str[str.length() - 1] = 'd';
std::cout << str << '\n';
std::cout << a.getVec()[0] << std::endl;
}
output:
abd
abc
expecting:
abd
abd
I would expect that since the A::save returns a reference to the last element of the vector, the changes made into that element would be commit into vector as well (becuase of that reference). But it apparently does not. Why?