#include <iostream>
#include <string>
#include <vector>
class SampleClass
{
public:
SampleClass(){}
void ReceiveNewMessage()
{
const auto msg = GenerateSomeRandomMessage();
StoreUniqueMessage(msg);
}
private:
void StoreUniqueMessage(std::string msg)
{
messages.push_back(msg);
}
std::string GenerateSomeRandomMessage()
{
return "Random message";
}
std::vector<std::string> messages{};
};
int main() {
SampleClass sc;
sc.ReceiveNewMessage();
return 0;
}
Clang is suggesting to use the following signature:
void StoreUniqueMessage(const std::string& msg);
However, as references are an alias for its referent, the behaviour is undefined when the referent is destroyed (correct me if wrong); in this case, within ReceiveNewMessage(), the variable msg is local to this function, but, if I use a reference to it in StoreUniqueMessage(), wouldn't it be undefined behaviour when the function is out of scope? What am I missing about references?
If you have
const std::string &msgand astd::vector<std::string> messages, the operationmessages.push_back(msg);makes a copy.The vector owns its contents and takes care of them.
That the reference becomes invalid after that is no longer a problem.
If you had a vector of pointers to strings that someone else owns, the situation would be different.