LearnFrenzy
Sign in Take a free test

C++ Programming · Topic 7 of 27

References: lvalue and rvalue

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

Coding Techniques

References: lvalue and rvalue · Study material

Sink parameters: take by value, then std::move

When a function stores its argument, take it by value and move it into place. Callers passing an lvalue pay one copy; callers passing a temporary pay only moves – one function covers both cases. Return members as const references to avoid copies.

#include <iostream>
#include <string>
#include <utility>

class Employee {
    std::string name_;
public:
    explicit Employee(std::string name) : name_(std::move(name)) {}   // take by value, then move into place
    const std::string& name() const { return name_; }                 // return a const reference to a member
};

int main() {
    std::string n = "Kavya Iyer";
    Employee a(n);                       // one copy (into the parameter), then a move
    Employee b(std::string("Arjun"));    // only moves
    std::cout << a.name() << " | " << b.name() << " | " << n << '\n';
    return 0;
}

Output

Kavya Iyer | Arjun | Kavya Iyer

Choose the parameter type by intent

IntentParameter
read a small valueint x
read a large objectconst T& x
modify the caller's objectT& x
keep a copy / take ownershipT x then std::move(x)
optional objectT* x or std::optional<T>
forward anything (templates)T&& x + std::forward<T>(x)

Write a perfect-forwarding factory

#include <memory>
#include <utility>

template <typename T, typename... Args>
std::unique_ptr<T> make(Args&&... args) {
    return std::unique_ptr<T>(new T(std::forward<Args>(args)...));   // what std::make_unique does
}

auto p = make<std::string>(5, '*');          // forwards 5 and '*' to std::string's constructor

Avoid dangling references from containers

std::vector<std::string> names{"a", "b"};
std::string& first = names.front();
names.push_back("c");          // may reallocate: first is now dangling
std::cout << first;            // undefined behaviour

// Safe: keep an index, or re-read after modifying
std::size_t idx = 0;
names.push_back("d");
std::cout << names[idx];

Good reference habits

  • Pass large read-only objects as const T&.
  • Use T& parameters only when the function really modifies the argument.
  • Return references only to objects that outlive the call.
  • Use const auto& in range-for loops unless you need copies or changes.
  • Apply std::move only to objects you will not read again.
  • Use std::forward exactly once per forwarding reference.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About C++ Programming

C++ adds object-oriented programming, templates and the powerful Standard Template Library (STL) to C. It powers game engines, browsers, trading systems and most competitive programming. This section takes you from basic syntax to classes, inheritance, polymorphism, modern C++ (C++11 to C++23) and the STL – every concept with runnable examples and practice questions checked on a real compiler.

Why it matters

  • OOP concepts – classes, inheritance, polymorphism, encapsulation – are asked in almost every interview
  • C++ with the STL is the most popular language for competitive programming and DSA rounds
  • Questions on constructors, virtual functions, references and smart pointers decide technical rounds
  • Modern C++ skills are in demand at product companies, fintech and game studios

Who it is for

  • School students (Class 11–12 computer science with C++) preparing for board exams and practicals
  • College students (B.Tech, BCA, MCA) learning OOP and data structures for semester exams and labs
  • Freshers preparing for placements, coding tests and C++ technical interviews
  • Competitive programmers who want to master the STL

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs that train you to spot bugs quickly
  • Complete programs with solutions and real output, verified on a compiler

Asked in

  • Campus placements
  • Product company interviews
  • Coding rounds & DSA
  • Competitive programming
  • GATE CS
  • University exams

How to use this section

  1. Read the study material of a topic and run the examples yourself.
  2. Practise the four exercises – MCQs, output, errors, programs – and read every explanation.
  3. Test yourself with the timed online test, then revise the topics you got wrong.

Search LearnFrenzy

Esc

Quick links