C++ Pass By Value Vs Pass By Reference

10 min read

Understanding how data moves between functions is a fundamental milestone for every C++ developer. That's why the distinction between pass by value and pass by reference dictates not only whether a function can modify the original variable but also has profound implications for performance, memory usage, and program correctness. Mastering these mechanisms allows you to write efficient, predictable, and modern C++ code.

The Core Concept: Copies vs. Aliases

At the highest level, the difference is simple. Conversely, when you pass by reference, the function parameter becomes an alias—an alternative name—for the original object. Any modifications made inside the function affect only this local copy; the original object in the calling scope remains untouched. Because of that, when you pass an argument by value, the function creates a distinct copy of the object. No copy is made; operations on the parameter directly manipulate the original variable.

This fundamental behavior shapes the entire architecture of your application. Choosing the wrong method can lead to subtle bugs where data isn't updated as expected, or catastrophic performance bottlenecks caused by unnecessary copying of large objects.

Deep Dive: Pass by Value

Pass by value is the default mechanism in C++ for non-reference parameters. When a function is called, the copy constructor of the object's class is invoked to initialize the parameter The details matter here..

Syntax and Mechanics

void modifyValue(int num) {
    num = 20; // Modifies the local copy only
}

int main() {
    int value = 10;
    modifyValue(value);
    // value is still 10
}

In this scenario, num is a completely independent integer residing in a different memory address (typically on the stack frame of modifyValue). For primitive types like int, double, or char, this copy operation is extremely fast—often optimized down to a single register move.

The Cost of Copying User-Defined Types

The performance story changes dramatically with classes and structs. Consider a std::vector<int> containing one million elements Most people skip this — try not to..

void processVector(std::vector vec) { // Pass by value
    // vec is a DEEP COPY of the original vector
    // Memory allocation + 1,000,000 element copies occur here
    vec.push_back(99); 
}

Passing this vector by value triggers a deep copy: memory is allocated on the heap for the new vector, and every single element is copied over. This is an O(N) operation in both time and memory. If this function is called in a tight loop, the application will grind to a halt due to allocation overhead and cache misses Which is the point..

When Pass by Value is Correct

Despite the overhead, pass by value has legitimate, modern use cases—specifically sink arguments and move semantics. g.If a function needs to take ownership of an object and store it (e., a constructor storing a member variable), passing by value allows the caller to decide whether to move or copy.

This is where a lot of people lose the thread.

class Widget {
    std::string name_;
public:
    // Efficient: accepts lvalues (copies) and rvalues (moves)
    Widget(std::string name) : name_(std::move(name)) {} 
};

Here, passing std::string by value enables the "pass by value and move" idiom. If the caller passes a temporary (Widget("Gadget")), the move constructor steals the resources. If the caller passes a named variable, a copy occurs, followed by a move into the member. This flexibility often outweighs the cost of a single move operation Not complicated — just consistent..

Not the most exciting part, but easily the most useful.

Deep Dive: Pass by Reference

Pass by reference avoids the copy entirely. Still, the parameter binds directly to the memory address of the argument. In C++, this is denoted by the & symbol in the parameter declaration Worth keeping that in mind..

Lvalue References (Type&)

An lvalue reference binds to a named object (an lvalue). It allows the function to read and modify the original object.

void modifyReference(int& num) {
    num = 20; // Modifies the original variable
}

int main() {
    int value = 10;
    modifyReference(value);
    // value is now 20
}

This is the standard way to implement "output parameters" or to modify an object's state without the overhead of copying. For large objects like containers, strings, or complex data structures, passing by reference is O(1)—constant time—regardless of the object's size.

Const References (const Type&)

This is arguably the most important parameter passing convention in pre-C++11 code and remains vital today. A const reference binds to an object but forbids modification through that reference.

void printLargeObject(const std::vector& vec) {
    // vec cannot be modified here
    // No copy is made; read-only access to original data
    for (int n : vec) std::cout << n << ' ';
}

Benefits of const Type&:

  1. Performance: Zero copy overhead for large objects.
  2. Safety: Compiler enforces read-only access.
  3. Polymorphism: Allows passing derived class objects to functions expecting a base class reference without object slicing (a critical issue with pass by value).
  4. Temporaries: C++ extends the lifetime of a temporary object bound to a const reference, allowing expressions like printLargeObject({1, 2, 3}); to work safely.

Rvalue References (Type&&) and Move Semantics

Introduced in C++11, rvalue references bind to temporaries (rvalues) or objects explicitly cast via std::move. They are the backbone of move semantics, enabling the efficient transfer of resources (heap memory, file handles, sockets) from a dying object to a new one But it adds up..

void stealResources(std::vector&& vec) {
    // vec is an rvalue reference. We can "move" from it.
    std::vector local = std::move(vec); // Cheap pointer swap
}

While rvalue references are technically a form of pass by reference, their semantic meaning is distinct: "I am going to pilfer this object's guts." They are rarely used as general function parameters outside of perfect forwarding templates or explicit sink functions Easy to understand, harder to ignore..

Performance Comparison: The Numbers Don't Lie

To visualize the impact, imagine a struct containing a std::array<double, 1000> (8KB of data) Not complicated — just consistent. Surprisingly effective..

Scenario Pass by Value Pass by const&
Operation Copy 8KB (memcpy) Pass pointer (8 bytes)
CPU Cycles ~2,000 - 5,000+ ~1 - 3
Cache Impact High (pollutes L1/L2) Negligible
Heap Allocations None (stack/array) but bandwidth heavy None

For a std::vector (dynamic allocation), pass by value involves a heap allocation, a loop to copy elements, and a deallocation upon function exit. Pass by reference involves none of that Nothing fancy..

Rule of Thumb:

  • Small, trivially copyable types (int, double, float, bool, char, small structs < 16-32 bytes): Pass by Value. It fits in registers, avoids pointer indirection, and allows compiler optimizations (like scalar replacement of aggregates).
  • Large types, non-trivial copy constructors, polymorphic types: Pass by const& (read-only) or Type& (read-write).
  • Sink parameters (consuming ownership): Pass by Value (leveraging move semantics).

The Sink Parameter Idiom in Practice

The "pass by value for sink parameters" rule deserves a concrete example, because it looks wasteful at first glance:

class UserRegistry {
    std::vector users_;
public:
    // Sink parameter: by value, then move into place.
    void addUser(std::string name) {
        users_.push_back(std::move(name));
    }
};

Consider the three call sites:

std::string n = "alice";
reg.addUser(n);                    // 1 copy (into parameter) + 1 move
reg.addUser(std::string("bob"));   // 1 move (into parameter) + 1 move
reg.addUser("carol");              // 1 construction + 1 move

The alternative — void addUser(const std::string&) — needs a copy inside the body for the first two cases, and the Type&& overload pair needs two functions to maintain. By-value sinks collapse all three cases into a single overload with optimal cost, and the caller's intent is expressed at the call site.

Most guides skip this. Don't.

The

The sink parameter is especially useful for move‑only types such as std::unique_ptr, std::vector, or any custom class that defines a deleted copy constructor but provides a move constructor. By taking the parameter by value, the function gains ownership of the caller's resource without imposing an extra const& indirection:

class FileHandler {
    std::unique_ptr fp_;
public:
    // Sink for a file path – the handler takes ownership of the string.
    void setPath(std::string path) {
        // No copy; `path` is moved into the internal buffer.
        fp_.reset(fopen(path.c_str(), "r"));
    }
};

Here the caller can pass a temporary (setPath("config.Consider this: txt")), a named variable (std::string p = "config. txt"; setPath(p);), or even a std::string returned from another function, and the cost is always a single move (or a construction followed by a move). Using const std::string& would force a copy for the first two forms, while an std::string&& overload would require two overloads to cover both lvalue and rvalue callers.

When a Sink Is Not the Right Choice

The by‑value rule is not a universal panacea. There are scenarios where you deliberately want to keep the argument alive after the call:

  • Read‑only access – If the function never modifies the object and does not intend to steal its resources, const& is clearer and cheaper:
    void logMessage(const std::string& msg);
    
  • Optional mutation – When the function may either read or move the argument depending on runtime state, a const& overload plus a separate sink overload lets the caller choose:
    void process(std::string s);          // sink – may move
    void process(const std::string& s);   // read‑only path
    
  • Recursive or mutually recursive calls – Passing large objects by value can cause unnecessary copying if the function itself calls itself with the same argument. In such cases a const& (or a pointer/reference) avoids the recursion overhead.

Interaction with Perfect‑Forwarding Wrappers

The sink idiom dovetails naturally with perfect‑forwarding templates. A function template that forwards its arguments into a sink can preserve move semantics while still being generic:

template
void emplace(Args&&... args) {
    // `emplace` becomes a sink for each argument it consumes.
    storage_.emplace(std::forward(args)...);
}

Because the template parameter pack is forwarded as Args&&, temporaries are moved, lvalues are copied (if the underlying constructor requires a copy), and the caller’s intent is retained. g.In practice, this pattern is the backbone of many modern libraries (e. , std::vector::emplace_back).

Summary Checklist

Situation Recommended Parameter Type Rationale
Small, trivially copyable (≤ 16 B) by value Fits in registers, no indirection, enables scalar replacement.
Large, expensive‑to‑copy (e.g.So , std::vector, std::string) const& (read‑only) or & (read/write) Avoids copy, cheap pointer pass‑through.
Move‑only ownership transfer by value (sink) Guarantees a single move, clean overload set, expresses intent.
Optional read/write Overload set (const& + by value) Gives caller flexibility without hidden copies.
Perfect‑forwarding context Template with T&& forwarding references Preserves move semantics across generic code.

By internalizing these guidelines, you can write functions that are both efficient and expressive. The sink parameter, in particular, turns what looks like a wasteful by‑value pass into a powerful mechanism for transferring ownership with minimal overhead. It aligns the interface with the underlying resource‑management semantics, reduces the number of overloads you must maintain, and lets the compiler do

what it does best: optimize away unnecessary copies and moves. When you treat parameters as sinks for ownership or references for observation, you make the data flow explicit—not just to the compiler, but to every human who reads the code.

That clarity pays dividends during maintenance. A function signature that takes std::unique_ptr<Widget> by value screams “I take ownership”; one that takes Widget& whispers “I’ll observe or mutate, but the caller keeps the deed.” The sink idiom extends that vocabulary to movable value types, letting std::string, std::vector, or your own heavy objects participate in the same expressive contract without a forest of std::move calls at the call site.

In practice, adopting these patterns shifts the performance conversation from “how do I avoid this copy?” to “who owns this object right now?”—a question the type system can answer for you. The result is code that runs faster and documents its own intent, which, after all, is the hallmark of modern C++.

Still Here?

Newly Published

Kept Reading These

Related Posts

Thank you for reading about C++ Pass By Value Vs Pass By Reference. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home