C++11新特性之 rvalue Reference(右值引用)
2021/8/3 11:06:26
本文主要是介绍C++11新特性之 rvalue Reference(右值引用),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
#include <iostream> int getValue () { int ii = 10; return ii; } int main() { std::cout << getValue(); return 0; }
root@ubuntu:~/c++# g++ -std=c++11 right.cpp -o auto root@ubuntu:~/c++# ./auto 10
右值有更隐晦的,记住如果一个表达式的结果是一个暂时的对象,那么这个表达式就是右值
这里需要注意的是 getValue() 是一个右值。
我们只能这样做,必须要有const
const int& val = getValue(); // OK int& val = getValue(); // NOT OK
#include <iostream> int getValue () { int ii = 10; return ii; } int main() { int & val = getValue(); return 0; }
root@ubuntu:~/c++# g++ -std=c++11 right.cpp -o auto right.cpp: In function ‘int main()’: right.cpp:11:25: error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’ int & val = getValue(); ^ root@ubuntu:~/c++#
#include <iostream> int getValue () { int ii = 10; return ii; } int main() { const int & val = getValue(); return 0; }
但是C++11中的右值引用允许这样做:
const int&& val = getValue(); // OK int&& val = getValue(); // OK
#include <iostream> int getValue () { int ii = 10; return ii; } int main() { const int & val = getValue(); const int && val2 = getValue(); int && val3 = getValue(); return 0; }
void printReference (const int& value) { cout << value; } void printReference (int&& value) { cout << value; }
第一个printReference()可以接受参数为左值,也可以接受右值。
而第二个printReference()只能接受右值引用作为参数。
#include <iostream> using namespace std; void printReference (int& value) { cout << "lvalue: value = " << value << endl; } void printReference (int&& value) { cout << "rvalue: value = " << value << endl; } int getValue () { int temp_ii = 99; return temp_ii; } int main() { int ii = 11; printReference(ii); printReference(getValue()); // printReference(99); return 0; }
root@ubuntu:~/c++# ./auto lvalue: value = 11 rvalue: value = 99
这篇关于C++11新特性之 rvalue Reference(右值引用)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15PingCAP 黄东旭参与 CCF 秀湖会议,共探开源教育未来
- 2024-05-13PingCAP 戴涛:构建面向未来的金融核心系统
- 2024-05-09flutter3.x_macos桌面os实战
- 2024-05-09Rust中的并发性:Sync 和 Send Traits
- 2024-05-08使用Ollama和OpenWebUI在CPU上玩转Meta Llama3-8B
- 2024-05-08完工标准(DoD)与验收条件(AC)究竟有什么不同?
- 2024-05-084万 star 的 NocoDB 在 sealos 上一键起,轻松把数据库编程智能表格
- 2024-05-08Mac 版Stable Diffusion WebUI的安装
- 2024-05-08解锁CodeGeeX智能问答中3项独有的隐藏技能
- 2024-05-08RAG算法优化+新增代码仓库支持,CodeGeeX的@repo功能效果提升