It makes no sense to discuss the performance of code that is incorrect, for example, your second fragment, whose behavior is undefined (usually this will crash your program). You cannot return references to automatic objects (allocated on the stack) local to the function.
It would be nice if, for example, your foo function was a member function of a class and returned a reference to a member of the class:
class C { public: set<string>& foo1 { return a_; } set<string> foo2 { return a_; } private: set<string> a_; }
In the above example, foo1 wil will be more efficient than foo2 because it will not create any new object, just return the link to the existing one.
source share