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:

  1. 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.
  2. 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.
  3. 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.

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

When to Use Default Arguments in C++ Functions
In what situations is it beneficial to use default arguments for function parameters?
Passing Arguments by Value vs Reference in C++
What is the difference between passing function arguments by value and by reference?
Best Practices for Function Overloading in C++
What are some best practices to follow when overloading functions in C++?
When to Use Forward Declarations in C++
In what situations should I use forward declarations in my C++ code?
Pros and Cons of Global Variables in C++
What are the advantages and disadvantages of using global variables in C++?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant