Is it always safe to use a reference of an object as an alias? For example, a string:
std::string test;
std::string &reftest( test );
std::cout << "test before: " << test << "\n";
std::cout << "reftest before: " << reftest << "\n";
reftest = "abc";
std::cout << "test after: " << test << "\n";
std::cout << "reftest after: " << reftest << "\n";
Is there a guarantee that reftest and test will always have the same string?
It helps if you think of a reference as a nickname. Even though you’re saying
reftest, you’re still referring totest. So, in short, yes.Note that there are some limitations. For example, the following is not standard:
but this
is, because a const reference can bind to a temporary, whereas a non-const one cannot.