右值引用的形参,使用时自动变成左值
#include <iostream>
#include <utility>
void f(int& x) {
std::cout << "lvalue reference overload f(" << x << ")\n";
}
void f(const int& x) {
std::cout << "lvalue reference to const overload f(" << x << ")\n";
}
void f(int&& x) {
std::cout << "rvalue reference overload f(" << x << ")\n";
}
int main() {
int i = 1;
const int ci = 2;
f(i); // calls f(int&)
f(ci); // calls f(const int&)
f(3); // calls f(int&&)
// would call f(const int&) if f(int&&) overload wasn't provided
f(std::move(i)); // calls f(int&&)
// rvalue reference variables are lvalues when used in expressions
int&& x = 1;
f(x); // calls f(int& x)
f(std::move(x)); // calls f(int&& x)
}
Rule& addElement(Element&& element)
{
// element在使用的时候会自动变成左值,需要用std::move强制转换右值
ruleElements.push_back(std::move(element));
return *this;
}
右值拷贝构造函数需要添加noexcept
?
Element(Element&& r) noexcept
{
*this = r;
printf("Element(Element&& r)\n");
}
|