C ++ 11右值参考与const参考 [英] C++11 rvalue reference vs const reference

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

问题描述

这可能很明显,但我认为这对我来说很难。鉴于此:

This may be obvious but I think it is something difficult to me. Given this:

void test(std::string&&) { }

std::string x{"test"};
test(std::move(x)); // ok

此代码调用 test()以右值引用作为参数,因此程序可以按我的期望进行编译。

This code calls test() with a rvalue reference as parameter so the program compiles as I expect.

现在看一下:

void other_test(const std::string&) { }

std::string x{"test"};
other_test(std::move(x)); // ok???

在这里,我很倾斜。为什么要编译此版本? std :: move 返回&&类型;为什么然后在使用 const& 的第二种方法中没有出现错误?

And here I'm tilted. Why does this version compile? The std::move returns a && type; why then I don't get an error in the second method where I use const&?

我知道

int&& s = 5;
const int& s = 5;

是有效的,因为在两种情况下,我提供的东西都不是左值,也没有地址。 & const& 是否相等?如果没有,是否存在差异?

is valid because in both cases I provide something that has not an lvalue, it has no addresses. Are && and const& equivalent? If no, are there differences?

推荐答案

std :: move 不会实际上并没有移走任何东西。这只是对 T&& 的演员的一个好名字。像这样的 test(std :: move(x));调用 test ; 仅显示 T& 可隐式转换为 const T& 。编译器发现 test 仅接受 const T& ,因此它转换了 T&&。 std :: move 返回到 const T& ,这就是全部

std::move doesn't actually move anything out of it's own. It's just a fancy name for a cast to a T&&. Calling test like this test(std::move(x)); only shows that a T&& is implicitly convertible to a const T&. The compiler sees that test only accepts const T& so it converts the T&& returned from std::move to a const T&, that's all there is to it.

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

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