June 11, 2026

Stop Passing Everything by const&

const T& is useful, but it should not be the default answer for every C++ parameter.

Many C++ codebases still treat const T& as the safe, professional choice. It looks efficient. It avoids copies. It works with almost everything. So it slowly becomes a habit:

void setEnabled(const bool& enabled);
void setTimeout(const std::chrono::milliseconds& timeout);
void setName(const std::string& name);
void setSocket(const std::unique_ptr<Socket>& socket);
void draw(const Point& point);

The problem is not that const T& is bad. The problem is that it often hides what the API really wants to say.

Sometimes the function only needs a cheap value. Sometimes it wants to store a copy. Sometimes it wants to take ownership. Sometimes it only wants a non-owning view. These are different contracts, but const T& makes many of them look the same.

Note

This article is not about replacing every reference with pass-by-value. It is about choosing the parameter type that communicates intent at the call site and inside the function.

Why const& became the default


The habit comes from a reasonable place. Copying a large object can be expensive, and passing by reference avoids that copy.

void process(const BigMessage& message);

For a large object that the function only reads, this is often exactly right. The function does not copy the object, does not take ownership, and does not modify it.

But this rule was often simplified into something much broader:

Common shortcut

“Passing by reference avoids copies, so use const T& unless you need to modify the argument.”

That shortcut misses several important cases in modern C++: cheap scalar types, move semantics, move-only types, non-owning views, and APIs that store their input.

First, ask what the parameter means


Before choosing between value and reference, ask what the function wants from the argument.

  • Does it need a small independent value? Pass by value.
  • Does it only read a large object? Pass by const&.
  • Does it store a copy? Often pass by value and move into storage.
  • Does it take ownership? Pass by value, especially for move-only types.
  • Does it only need to observe text or a range? Consider std::string_view or std::span.

The type should make that answer visible.

Cheap types should usually be passed by value


This is one of the most common places where const T& adds noise instead of value.

void setEnabled(const bool& enabled);
void setRetryCount(const int& retryCount);
void setTimeout(const std::chrono::milliseconds& timeout);
void moveTo(const Point& point);

For small types, a reference is not automatically cheaper. A reference is still something the function has to access indirectly. More importantly, it makes simple values look heavier than they are.

This is clearer:

void setEnabled(bool enabled);
void setRetryCount(int retryCount);
void setTimeout(std::chrono::milliseconds timeout);
void moveTo(Point point);

The function receives its own value. There is no lifetime question, no aliasing question, and no unnecessary visual complexity at the call site.

Tip

For arithmetic types, enums, small handles, iterators, durations, IDs, and small value objects, pass by value unless you have a concrete reason not to.

const& can hide ownership intent


Modern C++ APIs should make ownership visible. This is where defaulting to const T& often makes code harder to understand.

Consider this function:

void setName(const std::string& name)
{
    name_ = name;
}

The function stores the string. That means it must create or update its own copy. But the parameter type only says “I will read this string”.

When the caller passes an lvalue, copying is expected:

std::string name = readName();
user.setName(name);       // copy is expected

But when the caller passes a temporary, the API still copies from it:

user.setName(readName()); // still copies inside setName()

A common modern alternative is the sink parameter pattern:

void setName(std::string name)
{
    name_ = std::move(name);
}

Now the function clearly says: “give me a string value; I will keep my own copy of it.”

The call site also behaves naturally:

std::string name = readName();
user.setName(name);             // copies into parameter, then moves into member
user.setName(readName());       // moves temporary into parameter/member
user.setName("service-ready");  // builds the string once, then moves it

For setters, constructors, and functions that store their argument, passing by value often produces a cleaner API. It also lets the caller decide whether to copy or move.

Note

This is not a universal replacement for every const std::string&. If the function only reads the string and does not store it, a reference or a view may be a better fit.

The sink parameter pattern


A sink parameter is a parameter that the function consumes, stores, or takes ownership of. Passing it by value makes the contract explicit.

class Connection
{
public:
    explicit Connection(std::string endpoint)
        : endpoint_(std::move(endpoint))
    {
    }

private:
    std::string endpoint_;
};

This constructor does not simply inspect the endpoint. It stores it. The value parameter matches that behavior.

The same idea works well for many owning members:

class Service
{
public:
    Service(std::string name, std::vector<Route> routes)
        : name_(std::move(name))
        , routes_(std::move(routes))
    {
    }

private:
    std::string name_;
    std::vector<Route> routes_;
};

With this style, the constructor does not need separate overloads for lvalues and rvalues in many ordinary cases.

The caller can pass an existing value when it wants to keep it:

std::vector<Route> routes = loadRoutes();
Service service("api", routes); // routes is copied

Or it can explicitly move when it no longer needs the original object:

std::vector<Route> routes = loadRoutes();
Service service("api", std::move(routes)); // routes is moved

The API becomes easier to read because ownership transfer is visible at the call site.

Move-only types make the problem obvious


With move-only types, const T& often reveals that the API design is confused.

void setSocket(const std::unique_ptr<Socket>& socket);

What does this mean?

  • Does the function only want to use the socket temporarily?
  • Does it want to take ownership?
  • Does it store the pointer?
  • Can the argument be null?

The parameter type does not answer these questions well.

If the function only observes the socket, pass the object:

void configure(Socket& socket);
void inspect(const Socket& socket);

If null is meaningful, use a pointer:

void configure(Socket* socket);

If the function takes ownership, pass the std::unique_ptr by value:

void setSocket(std::unique_ptr<Socket> socket)
{
    socket_ = std::move(socket);
}

Now the call site tells the truth:

auto socket = std::make_unique<Socket>();
service.setSocket(std::move(socket));

The std::move is not noise. It is the caller acknowledging that ownership is transferred.

Warning

A const std::unique_ptr<T>& parameter often means the function is interested in the pointer wrapper, not the object. Most of the time, that is not what the API really wants to express.

Be careful with shared_ptr parameters


std::shared_ptr parameters deserve the same question: does the function need shared ownership, or does it only need the object?

void render(const std::shared_ptr<Widget>& widget);

If render only uses the widget during the call, the shared pointer is probably the wrong abstraction. The function can accept the object instead:

void render(const Widget& widget);

If the function stores shared ownership, pass the std::shared_ptr by value and move it into the member:

void setWidget(std::shared_ptr<Widget> widget)
{
    widget_ = std::move(widget);
}

That makes the ownership decision visible. Passing a std::shared_ptr says: “this function participates in ownership.” Passing Widget& or const Widget& says: “this function uses the object.”

Tip

Do not pass smart pointers just because the caller happens to store the object in a smart pointer. Pass the smart pointer only when pointer ownership is part of the function contract.

For read-only text, consider string_view


Another common habit is to use const std::string& for every text parameter.

bool hasPrefix(const std::string& text, const std::string& prefix);

If the function only reads the characters and does not store them, std::string_view may express the intent better:

bool hasPrefix(std::string_view text, std::string_view prefix);

This accepts strings, string literals, and other contiguous character ranges without forcing the API to talk specifically about std::string.

hasPrefix("systemd.service", "systemd");

std::string name = readServiceName();
hasPrefix(name, "systemd");

The important rule is that std::string_view is non-owning. It is excellent for parameters used during the call. It is dangerous if you store it without controlling the lifetime of the referenced characters.

class User
{
public:
    void setName(std::string_view name)
    {
        name_ = name; // OK: copies characters into owning std::string
    }

private:
    std::string name_;
};

But storing the view itself is a very different contract:

class UserView
{
public:
    explicit UserView(std::string_view name)
        : name_(name) // dangerous unless lifetime is guaranteed externally
    {
    }

private:
    std::string_view name_;
};

Warning

std::string_view does not own the characters. Use it when the function observes text, not when the object needs to own text for later.

For read-only ranges, consider span


The same idea applies to arrays and vectors. If a function only reads a contiguous range, it often does not need a specific container type.

Checksum calculateChecksum(const std::vector<std::byte>& data);

This says the caller must have a std::vector. But the algorithm only needs bytes.

Checksum calculateChecksum(std::span<const std::byte> data);

Now the function can work with a vector, array, or another contiguous buffer.

std::vector<std::byte> packet = readPacket();
calculateChecksum(packet);

std::array<std::byte, 16> header{};
calculateChecksum(header);

Again, the key is intent. The function observes a range. It does not own the range and does not require a specific container.

When const& is still the right choice


There are many good uses of const T&. The point is not to avoid it. The point is to use it when it says the right thing.

Use const T& when the function only reads an existing object and copying it would be unnecessary or expensive:

void validate(const Config& config);
void serialize(const Message& message, OutputStream& output);
void draw(const Scene& scene);
void compare(const Snapshot& before, const Snapshot& after);

These signatures are clear. The functions read existing objects. They do not take ownership. They do not store a new copy. They do not need a more general view type.

const T& is especially reasonable when:

  • T is expensive to copy.
  • The function only needs to read T during the call.
  • The API really wants that exact type, not just a view of its contents.
  • The function does not store the reference beyond the call.

Rule of thumb

Use const T& for large read-only objects. Use value for cheap values and sink parameters. Use views when the function only needs to observe text or ranges.

Do not optimize the wrong thing


Sometimes const T& is used because it feels like the safest performance choice. But API clarity is also a performance feature in real projects.

A function like this may avoid a copy:

void enableFeature(const bool& enabled);

But it makes a simple flag look like an object with lifetime concerns. The cost of misunderstanding the API is higher than the cost of copying a boolean.

Similarly, a setter like this may look efficient:

void setRoutes(const std::vector<Route>& routes)
{
    routes_ = routes;
}

But it prevents the caller from naturally moving data into the object:

void setRoutes(std::vector<Route> routes)
{
    routes_ = std::move(routes);
}

This version is often easier to use correctly, especially when the routes are produced just before the call.

A small decision table


Here is a practical starting point:

Function needsPreferExample
Small independent valuePass by valuevoid setTimeout(Duration timeout)
Read large objectconst T&void validate(const Config& config)
Store a copyPass by value, then movevoid setName(std::string name)
Take unique ownershipPass owning type by valuevoid setSocket(std::unique_ptr<Socket> socket)
Share ownershipPass std::shared_ptr by valuevoid setWidget(std::shared_ptr<Widget> widget)
Observe textstd::string_viewbool startsWith(std::string_view text)
Observe contiguous rangestd::spanChecksum crc(std::span<const std::byte> data)

This table is not a replacement for thinking. It is a way to avoid using const T& before asking what the function actually needs.

Common mistakes


A few patterns show up often in code reviews.

  • Passing cheap types by const&. It adds indirection and visual noise without improving the API.
  • Using const std::string& for read-only text APIs. Sometimes std::string_view is a better expression of intent.
  • Using const std::unique_ptr<T>& to observe an object. Prefer T&, const T&, or T* depending on nullability and mutability.
  • Using const std::shared_ptr<T>& everywhere. If ownership is not part of the function contract, pass the object instead.
  • Writing setters that always copy from const&. For stored values, pass by value and move into the member when that keeps the API simpler.
  • Assuming const& means no cost. It avoids a copy, but it may introduce indirect access, lifetime assumptions, and unclear ownership.

Watch the call site


Good parameter types make the call site easier to understand.

This call does not communicate ownership transfer:

service.setSocket(socket);

This one does:

service.setSocket(std::move(socket));

This call does not need to expose a string type:

hasPrefix("org.freedesktop.systemd1", "org.freedesktop");

So the parameter type can focus on what the function needs: a view of characters.

bool hasPrefix(std::string_view text, std::string_view prefix);

And this simple value should remain simple:

timer.setInterval(500ms);

The corresponding API does not need a reference:

void setInterval(std::chrono::milliseconds interval);

The best parameter type is often the one that makes the call site boring and obvious.

A practical review checklist


When you see const T& in an API, ask these questions:

  • Is T cheap to copy?
  • Does the function store the value?
  • Would moving from a temporary be useful?
  • Is ownership transfer part of the contract?
  • Is the function interested in the object or in the smart pointer wrapper?
  • Would a view type communicate the API better?

If the answer changes the meaning of the function, the parameter type should probably change too.

The key idea


If you remember only one thing, remember this:

Tip

Do not choose const T& because it feels safe. Choose the parameter type that describes the contract: value, reference, view, or ownership transfer.

const T& is great for large read-only objects. But it is not the best default for cheap values, sink parameters, move-only types, smart pointer ownership, text views, or range views.

Good modern C++ APIs do more than avoid unnecessary copies. They tell the caller what the function needs and what the function intends to do with the argument.