1

尝试更多地使用 rightvalues 但我很困惑,我应该如何设计我想要使用正确值的函数:

// Pass by whatever-it's-called
void RockyBalboa::DoSomething(std::string&& str){ 
     m_fighters.push_back(str);
}
// Pass by reference
void RockyBalboa::DoSomething(std::string& str){
     m_fighters.push_back(std::move(str)); 
}

这两个函数调用之间的有效区别是什么?当我用双&符号传递它使用时会发生什么std::move

4

1 回答 1

2

你已经交换了用法。它是可以移动的右值引用。左值参考应该是const

// Rvalue reference
void RockyBalboa::DoSomething(std::string&& str){ 
     m_fighters.push_back(std::move(str));
}
// Lvalue reference
void RockyBalboa::DoSomething(const std::string& str){ // note: const
     m_fighters.push_back(str);
}

但是,您可以使用转发引用来涵盖这两种情况:

#include <type_traits>

// Forwarding reference
template<typename T>
void RockyBalboa::DoSomething(T&& str) {
    // Create a nice error message at compile time if the wrong type (T) is used:
    static_assert(std::is_convertible_v<T, std::string>);

    m_fighters.emplace_back(std::forward<T>(str));
}
于 2020-08-25T09:45:47.647 回答