Rvalue references

文章目录
  1. 1. Rvalue-references
    1. 1.1. Perfect Forwarding

Rvalue-references

Rvalue references are a new reference type introduced in C++0x that help solve the problem of unnecessary coping and enable perfect forwarding. When the right-hand side of an assignment is an rvalue, then the left-hand side object can steal resources from the right-hand side object rather than performing a seperate allocation, thus enabling move semantics.

Lvalue: 可以出现于 operator = 左侧者

Rvalue: 只能出现于 operator = 右侧者

只要在内存中有确定存储空间的都是左值。

1
2
3
4
5
6
7
int foo() {
return 5;
}

int x = foo(); // ok
int *p = &foo(); // error 对着右值 5 取其 reference 是不可以的。没有所谓的 Rvalue reference(before C++0x)
foo() = 7; // error

当 Rvalue 出现于 operator=(copy assignment)的右侧,我们认为对其资源进行偷取/搬移(move) 而非拷贝(copy)是可以的。

那么:

  1. 必须有语法让我们在调用端告诉编译器,这是个“Rvalue”
  2. 必须有语法让我们在被调用端写出一个专门处理 Rvalue 的所谓 move assignment 函数。

Perfect Forwarding

Perfect forwarding allows you to write a single function template that takes n arbitrary arguments and forwards them transparently to another arbitrary function. The nature of the argument(modifiable, const, lvalue, rvalue) is preserved in the forwarding process.

1
2
3
4
template<typename T1, typename T2>
void functionA(T1&& t1, T2&& t2) {
functionB(std::forward<T1>(t1), std::forward<T2>(t2));
}