Introduction to Functions

Returning by Value vs Reference in C++

When should I return by value from a function, and when should I return by reference?

Abstract art representing computer programming

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.

This Question is from the Lesson:

Introduction to Functions

Learn the basics of writing and using functions in C++, including syntax, parameters, return types, and scope rules.

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

Introduction to Functions

Learn the basics of writing and using functions in C++, including syntax, parameters, return types, and scope rules.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved