【Cherno的C++视频】Lvalues and Rvalues in C++

本文深入探讨了C++中的左值和右值引用,包括它们的定义、作用以及如何在函数参数中使用。通过示例代码展示了左值引用、常量左值引用和右值引用如何影响变量的赋值和临时对象的处理。理解这些概念对于优化C++代码和利用移动语义至关重要。
摘要由CSDN通过智能技术生成
#include <iostream>

// move semantics
// L values are basically variables that have some storage back in them.
// R value are temporary values.

int& GetValue()
{
	static int value = 10;
	return value;
}

void SetValue(int value)
{

}

void PrintName(std::string& name)//L value reference only accept L values.
{
	std::cout << "[Lvalue]: " << name << std::endl;
}
void PrintName(const std::string& name)//const L value reference accept  L values and temporaries R values.
{
	std::cout << "[Lvalue and temporaries R values]: " << name << std::endl;
}
void PrintName(std::string&& name)//R value reference only accept R values.
{
	std::cout << "[Rvalue]: " << name << std::endl;
} 
int main(void)
{
	int i = 10;//in this case, L value is sth on the left side of the equal sign. i->L value, 10->R value.
	int a = i;
	int b = GetValue();
	GetValue() = 5;
	SetValue(10);//calling SetValue() with an L value.
	SetValue(i);//calling SetValue() with an R value;

	//			L value		  R value
	std::string firstName	= "Yan";
	std::string lastName	= "Chernikov";
	std::string fullName	= firstName + lastName;

	PrintName(firstName);
	PrintName(firstName + lastName);

	std::cin.get();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值