Pass by value vs pass by rvalue reference

前端 未结 7 990
独厮守ぢ
独厮守ぢ 2020-11-29 01:40

When should I declare my function as:

void foo(Widget w);

as opposed to

void foo(Widget&& w);?

Assume this

7条回答
  •  萌比男神i
    2020-11-29 01:46

    The rvalue reference parameter forces you to be explicit about copies.

    Yes, pass-by-rvalue-reference got a point.

    The rvalue reference parameter means that you may move the argument, but does not mandate it.

    Yes, pass-by-value got a point.

    But that also gives to pass-by-rvalue the opportunity to handle exception guarantee: if foo throws, widget value is not necessary consumed.

    For move-only types (as std::unique_ptr), pass-by-value seems to be the norm (mostly for your second point, and first point is not applicable anyway).

    EDIT: standard library contradicts my previous sentence, one of shared_ptr's constructor takes std::unique_ptr&&.

    For types which have both copy/move (as std::shared_ptr), we have the choice of the coherency with previous types or force to be explicit on copy.

    Unless you want to guarantee there is no unwanted copy, I would use pass-by-value for coherency.

    Unless you want guaranteed and/or immediate sink, I would use pass-by-rvalue.

    For existing code base, I would keep consistency.

提交回复
热议问题