Reputation: 3388
set<string> foo {
set<string> a;
// operation on a
return a;
}
Is there any performance difference if I do:
set<string>& foo {
set<string> a;
// ops on a
return a;
}
If so, my understanding is that a will be allocated on stack. After foo() returns, the memory space will be reclaimed. How can we reference to a memory which is claimed?
Upvotes: 4
Views: 150
Reputation: 26164
There is no point discussing performance of a code which is not correct, like your second snippet, which behaviour is undefined (this will normally make your program crash). You cannot return references to automatic objects (allocated on stack), local to the function.
It would be ok if, for example, your foo
function was a member function of a class, and was returning 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 be more efficient than foo2
cause it will not create any new object, just return a reference to the existing one.
Upvotes: 1
Reputation: 275230
In case B, any actual use of the returned value results in undefined behavior. You are not allowed to return a local automatic variable by reference and expect anyone to be able to access it.
See this live work space warning message. Your compiler will usually warn you when you do something like that, but relying on it is not always advised.
Note that in C++11, the first example is highly efficient. Betweeen lvalue reference based move and NRVO, the cost to return a local std::vector<std::string>
by value is on the order of a few ifs and copying a 32 bits of memory, or in some cases less (ie, actually zero cost, because the std::set
gets constructed in the callers scope directly).
Upvotes: 5