如何获得对右值的引用? [英] How is it possible to get a reference to an rvalue?

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

问题描述

我在C ++中使用了 std :: move std :: forward 。我的问题是:标准库实际上如何实现这些功能?



如果左值是您可以获取的地址,而右值不是左值,您实际上如何实现这些引用?



这些新功能是否允许类似的东西:

 自动x =&(3); 

还是类似的东西?您能否获得对不只是 std :: move / forward 返回的左值的右值的引用? / p>

希望这些问题有道理。我在Google上找不到很好的信息,只是在完美转发等方面找不到教程。

解决方案

我无法调用函数: void foo(string * bar)像这样: foo(& string( Hello World!))或我收到错误:


错误:获取临时地址


我也不能调用函数: void foo(string& bar)像这样: foo(string( Hello World! ))或出现错误:


错误:类型'std的非常量引用无效的初始化:: string& {aka std :: basic_string&}'来自类型为'std :: string {aka std :: basic_string}'的右值


C ++ 11为我提供的功能是做一个右值引用,所以我可以调用一个函数: void foo(string&& bar)像这样: foo(string( Hello World!));



此外,在 foo 内部,我可以获取右值引用传递的对象的地址:

  void foo(string&& bar){
string * temp =& bar;

cout<< * temp<< @:<<临时<<恩德尔
}

似乎OP对rvalue的掌握非常好。但是对此的解释对我有帮助,可能对其他人也有帮助。其中详细介绍了为什么C ++ 03允许常量引用rvalue,而C ++ 11允许常量引用rvalue。


I have used std::move and std::forward in C++. My question is: how are these functions actually implemented by the standard library?

If an lvalue is something you can get the address of, and an rvalue is exclusively not an lvalue, how can you actually implement these references?

Do these new facilities allow for something like:

auto x = &(3); 

or something like that? Can you get a reference to an rvalue that isn't just a std::move/forward returned lvalue?

Hopefully these questions make sense. I couldn't find good information on Google, just tutorials on perfect forwarding, etc.

解决方案

I cannot call a function: void foo(string* bar) like this: foo(&string("Hello World!")) or I get an error:

error: taking address of temporary

I also cannot call a function: void foo(string& bar) like this: foo(string("Hello World!")) or I get an error:

error: invalid initialization of non-const reference of type 'std::string& {aka std::basic_string&}' from an rvalue of type 'std::string {aka std::basic_string}'

What C++11 has provided me the ability to do is to make an rvalue reference, so I can call a function: void foo(string&& bar) like this: foo(string("Hello World!"));

Furthermore, internally to foo I can get the address of the object passed in by an rvalue reference:

void foo(string&& bar){
    string* temp = &bar;

    cout << *temp << " @:" << temp << endl;
}

It seems like the OP has a really good grip on rvalues. But this explanation of them was helpful to me, and may be to others. It goes into a bit of detail about why C++03 allowed constant references to rvalues, versus C++11's rvalue references.

这篇关于如何获得对右值的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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