Abseil C++

An open-source collection of C++ library code designed to augment the C++ standard library

  • Tip of the Week #117: Copy Elision and Pass-by-value
    https://abseil.io/tips/117

    Originally posted as TotW #117 on June 8, 2016

    by Geoff Romer, (gromer@google.com)

    “Everything is so far away, a copy of a copy of a copy. The insomnia distance of everything, you can’t touch anything and nothing can touch you.” — Chuck Palahniuk

    Suppose you have a class like this:

    class Widget public: …

    private: string name_; ;

    How would you write its constructor? For years, the answer has been to do it like this:

    // First constructor version explicit Widget(const std::string& name) : name_(name)

    However, there is an alternative approach which is becoming more common:

    // Second constructor version explicit Widget(std::string name) : name_(std::move(name))

    (If you’re not familiar with std::move(), see TotW #77, or pretend I used std::swap instead; the same principles apply). (...)