Skip to content

Pass by const ref #37

@vladon

Description

@vladon

cppbestpractices/04-Considering_Safety.md

Also, using const & prevents the compiler from copying data unnecessarily.

If you internally copy object to internal var, the better variant will be passing params by value.

First example marked as "Bad Idea":

// Bad Idea
//...
MyClass(std::string t_value)
    : m_value(t_value)
  {
  }
// ...
std::string m_value;

When you do m_value(t_value) in constructor initialization list, it is anyway will be a copy, it doesn't matter you pass it by const ref or by value.

But passing by value in such situations (when you copy contents to internal variable) is much more better: it is thread-safe, no dangling refs, you can pass rvalues, you can construct in-place, etc.

There will not be two copies, see copy elision.

So, in given example it is not a Bad Idea.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions