C ++,函数参数中的右值引用 [英] C++, rvalue references in function parameters

查看:147
本文介绍了C ++,函数参数中的右值引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解 rvalue 引用。我已经看到它们如何在构造函数中使用,例如 std :: move std :: forward 之类的东西,但是我仍然不明白为什么这行不通:

I'm trying to understand rvalue references. I have seen how they are used in constructors, with things like std::move and std::forward, but I still don't understand why this doesn't work:

void func(string&& str)
{
    cout << str << endl;
}
int main(int argc, char* argv[])
{
    string s("string");
    func(s);
}

这样做:

template<typename T>
void func(T&& str)
{
    cout << str << endl;
}
int main(int argc, char* argv[])
{
    string s("string");
    func(s);
}

为什么与功能模板版本一起使用?

Why does it work with the function template version?

推荐答案

就像@Peter说的那样, T 的类型推导为 string& ,而C ++的引用折叠规则则说:

Like @Peter said, the type of T is deduced as string&, and C++’s reference-collapsing rule says:


T& & ⇒T& //来自C ++ 98

T&& & ⇒T& // C ++ 0x

T&的新功能&& ⇒T& // C ++ 0x

T&&中的新功能&& ⇒T&& // C ++ 0x的新功能

T& & ⇒ T& // from C++98
T&& & ⇒ T& // new for C++0x
T& && ⇒ T& // new for C++0x
T&& && ⇒ T&& // new for C++0x

所以 func 的实例是实际上:

void func(string& str)

它有效。

这篇关于C ++,函数参数中的右值引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆