C ++ puzzle about return value by reference

set<string> foo { set<string> a; // operation on a return a; } 

Is there a difference in performance if I do:

 set<string>& foo { set<string> a; // ops on a return a; } 

If so, I understand that a will be allocated on the stack. After returning foo (), the memory space will be restored. How can we refer to a memory that is declared?

+4
source share
2 answers

In case B, any actual use of the return value results in undefined behavior. You are not allowed to return a local automatic variable by reference and expect anyone to be able to get it.

See this warning message live workspace . Your compiler usually warns you when you do something similar, but relying on it is not always recommended.

Note that in C ++ 11, the first example is very efficient. Betweeen laleue reference based move and NRVO, the cost of returning a local std::vector<std::string> by value is of the order of several ifs and copies 32 bits of memory, or in some cases less (i.e. Actually zero cost, because std::set is created directly in the caller area).

+5
source

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.

+1
source

All Articles