Pass by value vs pass by rvalue reference

前端 未结 7 978
独厮守ぢ
独厮守ぢ 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条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-29 01:47

    One issue not mentioned in the other answers is the idea of exception-safety.

    In general, if the function throws an exception, we would ideally like to have the strong exception guarantee, meaning that the call has no effect other than raising the exception. If pass-by-value uses the move constructor, then such an effect is essentially unavoidable. So an rvalue-reference argument may be superior in some cases. (Of course, there are various cases where the strong exception guarantee isn't achievable either way, as well as various cases where the no-throw guarantee is available either way. So this is not relevant in 100% of cases. But it's relevant sometimes.)

提交回复
热议问题