Returning by Value vs Reference in C++
When should I return by value from a function, and when should I return by reference?
When deciding whether to return by value or by reference, consider these guidelines:
- If you're returning a local variable or a temporary, you must return by value. Returning a reference to a local variable or a temporary will result in undefined behavior, because the referenced object will be destroyed when the function ends.
- If you're returning a large object and want to avoid the cost of copying it, consider returning by const reference. This avoids the copy while still preventing the caller from modifying the object.
- If you want the caller to be able to modify the returned object, and the object will outlive the function call, you can return by non-const reference.
Here's an example of each:
#include <string>
// Returns by value
std::string getNameValue() { return "John"; }
// Returns by const reference
const std::string& getNameConstRef() {
static std::string name = "John";
return name;
}
// Returns by non-const reference
std::string& getNameRef() {
static std::string name = "John";
return name;
}
int main() {
std::string name1 = getNameValue();
const std::string& name2 = getNameConstRef();
std::string& name3 = getNameRef();
// Modifies the static variable in getNameRef
name3 = "Steve";
}
In general, prefer returning by value unless you have a good reason to return by reference.
Introduction to Functions
Learn the basics of writing and using functions in C++, including syntax, parameters, return types, and scope rules.