Assume there is a method which returns a std::set:
std::set<string> MyClass::myMethod() const
{
std::set<string> result;
// ... some code to fill result ...
return result;
}
In the caller side we can store result of myMethod in two ways:
void MyClass::test()
{
const std::set<string> s1 = myMethod(); // 1
const std::set<string>& s2 = myMethod(); // 2 (using reference)
// ... some code to use s1 or s2 ...
}
My questions are:
- Is there any difference between them?
- Which way is better and
efficient?
Theoretically, the second version is better because it doesn’t require the extra copy.
In practice, RVO will likely kick in so they should be about the same.