How to commit changes through reference from vector into that vector in C++?

Viewed 43

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?

1 Answers

When you wrote:

std::string str = a.save("abc");

The above statement creates a variable named str of type std::string and has a copy of the std::string(which was returned by reference) returned by the call expression a.save("abc"). That is, str is a copy of the element in the std::vector data member vec.

To get your desired output change the statement to as shown below:

std::string& str = a.save("abc");

Now, in the above statement, str is an alias for the std::string that was returned(by reference) by the call expression a.save("abc").

Related