google / styleguide

Style guides for Google-originated open-source projects

Home Page:https://google.github.io/styleguide/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

C++ "Inputs and Outputs" section improvement

d-uspenskiy opened this issue · comments

The "Inputs and Outputs" section contains the following text

Avoid defining functions that require a const reference parameter to outlive the call, because const reference parameters bind to temporaries. Instead, find a way to eliminate the lifetime requirement (for example, by copying the parameter), or pass it by const pointer and document the lifetime and non-null requirements.

Using of const pointer is not the best option in such situation. std::reference_wrapper<const T> could be used instead.

struct Filter {
    bool operator()(int value) const {
...
    }
};

struct Handler {
    explicit Handler(const Filter& filter) : filter_(filter) {}

    void operator()(int value) {
        if (filter_(value)) {
...
        }
    }

    const Filter& filter_;
};

...
Filter filter;
Handler handler{filter};
handler(10); // OK
...
Handler handler{Filter()};
handler(10); // Undefined behavior
...

Using of std::reference_wrapper in Filter's constructor makes second situation impossible

explicit Handler(std::reference_wrapper<const Filter> filter) : filter_(filter) {}

Hey @d-uspenskiy can you please elaborate what needs to be done. I would like to give this a try.

I absolutely disapprove of use of reference_wrapper for that purpose. Just because it appears in the standard doesn't mean it's useful, and in particular that class template is only designed to be useful in exotic contexts. It's useful for generic code that needs to support references in an almost-regular fashion (rare). It has so much special case handling (in CTAD, in structured bindings, etc) and is so full of edge cases ... it's really not a good habit to use.

Yes, technically you can solve that problem in that fashion, but in my professional opinion that's a solution that's far worse than the problem.