C++ 右值引用重载,而不是移动构造函数

c++ rvalue reference overload other than move constructor

本文关键字:移动 构造函数 引用 重载 C++      更新时间:2023-10-16

有人可以举一个函数重载的例子,说明一个重载了rValue引用参数的函数,而不是移动构造函数或移动赋值运算符,该函数充分利用了传递的参数是右值的事实? 因此,它执行函数的左值参数版本的功能,但除了使复制或赋值更有效之外,它还做了一些特殊的事情(仅仅是因为传递了右值)。 也许使其他一些操作更有效率? 更好的是,也许在某些情况下需要一些额外的东西,但无法用左值执行? 到目前为止,我想不出任何例子。

所以我问的是你自己的函数的重载:

void ping (const Person& person) {
    // do something 
}
void ping (Person&& person) {
    // do what the first ping does but take advantage of the fact that an rvalue (a temporary?) was passed 
}

许多其他运算符在标准库中都有右值引用重载,例如,字符串operator+重载:

template<class charT, class traits, class Allocator>
basic_string<charT,traits,Allocator>
operator+(const charT* lhs,
basic_string<charT,traits,Allocator>&& rhs);
template<class charT, class traits, class Allocator>
basic_string<charT,traits,Allocator>
operator+(basic_string<charT,traits,Allocator>&& lhs,
const charT* rhs);

当然,push_backemplace_back以及容器中其余的插入/置换函数系列:

void push_back(T&& x);
template <class... Args> void emplace_back(Args&&... args);