【问题标题】:c++ rvalue reference overload other than move constructorc++ 右值引用重载,而不是移动构造函数
【发布时间】:2013-12-19 21:49:41
【问题描述】:

谁能给出一个函数重载的例子,该函数使用 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 
}

【问题讨论】:

    标签: c++ constructor overloading move rvalue


    【解决方案1】:

    许多其他运算符在标准库中具有右值引用重载,例如,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 以及容器中的其余 insert/emplace 系列函数:

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

    【讨论】:

    • 以及任何可以完美转发的东西
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多