Understanding Reference and Pointer Types

Passing and Returning References

What should I be aware of when passing or returning references in C++?

Abstract art representing computer programming

When passing or returning references in C++, there are a few important things to keep in mind:

  1. Avoid returning references to local variables. Local variables are destroyed when the function returns, so returning a reference to a local variable will result in a reference to invalid memory.
  2. Be careful when storing a returned reference. If the reference was to a temporary object, that object will be destroyed and the reference will become invalid.
  3. Pass by const reference whenever possible to avoid unnecessary copying and to make it clear that the function will not modify the object.

Here's an example of a bad practice - returning a reference to a local variable:

int& BadFunction() {
  int x = 10;
  // Error: returning reference to local variable
  return x; 
}

Instead, you could return by value:

int GoodFunction() {
  int x = 10;
  return x; // Okay: returning by value
}

Or, if you really need to return a reference, make sure it's to a non-local variable:

int global_x = 10;

int& OkayFunction() {
  // Okay: returning reference to global variable
  return global_x;
}

But in general, returning by value is safer and often just as efficient due to compiler optimizations.

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

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