C++11左值和右值引用讲解

  • 左值引用,简单的来说,就是引用的对象的内存地址,改变内存地址的指向,引用的对象也会跟着改变,在语法的层面上来说,左值使用&符号,进行内存对象的指向的改变。
    示例代码:
void testLeftValueRef()
{
	// 左值引用内存对象,使用一个&来引用对象-- 所以y改变的话 x也改变
	int x = 444;
	int & y = x;
	y = y + 1123;
	cout << x << endl;
}

其中,对象y是一个左值引用,改变y的值,所引用的x对象也会跟着改变,运行结果:
在这里插入图片描述
可以看出,对象发生了改变。

  • 右值引用,即使用&& 进行引用对象。可以获取右值的内存地址。
    示例代码:
void testRightValueRef()
{
	// 右值引用 使用&&来表示,也是能获取地址的。
	const int aa_ = 123;
	int x = 133;
	int &&y_ = 133;
	cout << &y_ << endl;
}

在这里插入图片描述

  • 如果需要像左值一样,可以改变内存地址的指向对象的方法,可以使用C++11的std::move方法进行改变。
    示例代码:
void Redss()
{
	int ssq = 1233;
	int && aq = std::move(ssq); //右值引用
	ssq = 123123;
	cout << aq << endl;
}
  • 运行结果:
    在这里插入图片描述
    完整代码如下:
// VisuakBack.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include "pch.h"
#include <iostream>
#include <string.h>

using namespace std;

// 测试左值引用和右值引用


void testLeftValueRef()
{
	// 左值引用内存对象,使用一个&来引用对象-- 所以y改变的话 x也改变
	int x = 444;
	int & y = x;
	y = y + 1123;
	cout << x << endl;
}

void testRightValueRef()
{
	// 右值引用 使用&&来表示,也是能获取地址的。
	const int aa_ = 123;
	int x = 133;
	int &&y_ = 133;
	cout << &y_ << endl;
}

void RightLeftValue()
{
	// 左值和右值的相互引用
	int &&asa = 123;
	int &aad = asa;
	cout << aad << endl;
	aad = aad + 12123;
	cout << asa << endl;
}


void Redss()
{
	int ssq = 1233;
	int && aq = std::move(ssq); //右值引用
	ssq = 123123;
	cout << aq << endl;
}

int main()
{
	Redss();
}


发布了382 篇原创文章 · 获赞 122 · 访问量 40万+

猜你喜欢

转载自blog.csdn.net/Giser_D/article/details/104490985
今日推荐