正确的值作为函数参数,正确的用法?
Right values as function argument, correct usage?
尝试更多地使用右值但我感到困惑,我应该如何设计我想要使用正确值的函数:
// 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));
}
这两个函数调用之间有什么区别?当我用双符号传递它时会发生什么 and use std::move
?
你已经交换了用法。 Rvalue reference that can be moved. The Lvalue 参考应该是 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);
}
但是您可以使用 forwarding reference 来涵盖这两种情况:
#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));
}
尝试更多地使用右值但我感到困惑,我应该如何设计我想要使用正确值的函数:
// 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));
}
这两个函数调用之间有什么区别?当我用双符号传递它时会发生什么 and use std::move
?
你已经交换了用法。 Rvalue reference that can be moved. The Lvalue 参考应该是 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);
}
但是您可以使用 forwarding reference 来涵盖这两种情况:
#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));
}