c ++ rvalue引用和const限定符

c ++ rvalue引用和const限定符

问题描述:

const限定的许多好处之一是使一个API更容易理解,例如:

Among the many benefits of const qualification is to make an API more understandable, example:

template<typename T> int function1(T const& in);
// clearly, the input won’t change through function1

引用,可以从完美的转发中受益,但常常去除const限定符,例如:

With the introduction of rvalue references, one can benefit from perfect forwarding but often const qualifiers are removed, example:

template<typename T> int function2(T&& in);
// can explicitly forward the input if it's an rvalue

一个很好的方法来描述function2不会改变它的输入?

Apart from documentation, is there a good way to describe that function2 won’t change its input?


template<typename T> int function2(T&& in);
// can explicitly forward the input if it's an rvalue

一个好的方法描述
function2不会改变它的输入?

Apart from documentation, is there a good way to describe that function2 won’t change its input?

是的。坚持使用C ++ 03解决方案:

Yes. Stick with the C++03 solution:

template<typename T> int function1(T const& in);
// clearly, the input won’t change through function1

完美转发的好处是你不想假设如果某些 const 或非 - const ,lvalue或rvalue。如果你想强制执行的东西没有修改(即它是 const ),然后通过添加 const

The benefits of perfect forwarding are that you don't want to assume if something is const or non-const, lvalue or rvalue. If you want to enforce that something is not modified (i.e. that it is const), then explicitly say so by adding const.

您可以这样做:

template<typename T> int function1(T const&& in);
// clearly, the input won’t change through function1

代码会想知道你为什么使用右值引用。并且 function1 将停止接受lvalue。只需使用 const& ,每个人都会明白。这是一个简单而很好理解的成语。

However everyone who read your code would wonder why you've used rvalue references. And function1 would cease to accept lvalues. Just use const & instead and everyone will understand. It is a simple and well understood idiom.

你不想完全向前。您要强制执行不可变性。

You don't want to perfectly forward. You want to enforce immutability.