Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/neo4j/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 函数参数的值是否正确,用法是否正确?_C++_Parameter Passing_Rvalue Reference_Stdmove - Fatal编程技术网

C++ 函数参数的值是否正确,用法是否正确?

C++ 函数参数的值是否正确,用法是否正确?,c++,parameter-passing,rvalue-reference,stdmove,C++,Parameter Passing,Rvalue Reference,Stdmove,尝试更多地使用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){

尝试更多地使用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
时会发生什么?

您已经交换了用法。它是可以移动的引用。参考应为
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);
}
但是,您可以使用a来涵盖这两种情况:

#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));
}
#包括
//转发参考
模板
void RockyBalboa::DoSomething(T和str){
//如果使用了错误的类型(T),则在编译时创建一条漂亮的错误消息:
静态断言(std::is_convertible_v);
m_战斗机。后置(std::forward(str));
}

另一方面,应该移动
&
一个。太棒了,我实际上也需要forward,因为我有一个包装函数,它可以做类似
wrapper(std::string&&str){return g(std::string str)}
的事情,我现在改为
return g(std::forward(str))
@dejoma很高兴它有帮助!请仔细阅读有关转发参考资料的链接,尤其是以下部分:“转发引用是:1)函数模板的函数参数声明为对同一函数模板的cv类型模板参数的右值引用。2)
auto&
除非从括号内的初始值设定项列表推导:“。