Value Categories (L-Values and R-Values)

Returning L-value References from Functions

When is it appropriate to return an l-value reference from a function?

Illustration representing computer hardware

Returning an l-value reference from a function can be useful in certain scenarios, but it should be done with caution. Here are a few situations where returning an l-value reference might be appropriate:

  1. Returning a reference to a member variable: If a function needs to provide direct access to a member variable of an object, it can return an l-value reference to that member. This allows the caller to modify the member directly.

    class MyClass {
    public:
      int& GetValue() { return value; }
    
    private:
      int value;
    };
  2. Chaining function calls: Returning an l-value reference allows function calls to be chained together. This is commonly used in operator overloading or fluent interfaces.Usage:

    MyClass& MyClass::SetValue(int newValue) {
      value = newValue;
      return *this;
    }
    MyClass obj;
    obj.SetValue(10).SetValue(20);

However, it's important to note that returning references to local variables or temporary objects is dangerous and should be avoided. Doing so can lead to undefined behavior, as the referenced object may be destroyed when the function returns.

Additionally, returning a non-const l-value reference may violate const-correctness and allow the caller to modify the referenced object unexpectedly. If modification is not intended, consider returning a const l-value reference or a value instead.

This Question is from the Lesson:

Value Categories (L-Values and R-Values)

A straightforward guide to l-values and r-values, aimed at helping you understand the fundamentals

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

This Question is from the Lesson:

Value Categories (L-Values and R-Values)

A straightforward guide to l-values and r-values, aimed at helping you understand the fundamentals

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