C++ 左值 右值 移动构造函数 移动赋值运算符

本文介绍了C++中的左值、右值和右值引用的概念,通过示例展示了移动构造函数和移动赋值运算符的使用。移动构造函数和移动赋值运算符能提升效率,当类有自定义拷贝构造、拷贝赋值或析构时,编译器不会默认生成移动构造和移动赋值。满足特定条件时,编译器会生成默认的移动构造和移动赋值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、左值、右值、左值引用&、右值引用&&

main.cpp

#include <iostream>
using namespace std;

int main()
{
	string str = "I love china";
	const char *p = str.c_str();
	cout << (void*)p << endl;
	string &str1 = str;//str为左值, str1为左值引用
	string &&str2 = "I love china";//"I love china"为右值,str2为右值引用
	string str3 = std::move(str);//str左值转右值,只有转右值才会调用移动构造函数,否则调用的是拷贝构造函数。
	//调用了string的移动构造函数,原str为空,值转移到str3了
	const char *p1 = str3.c_str();
	cout << (void*)p1 << endl;//p和p1不一致,说明并不是名副其实的移动

	string str4 = "I love china";
	string && str5 = std::move(str4);//不会调用移动构造函数,只是个左值转右值
	str5 = "abc";//str5和str4同步修改
	str4 = "edf";//str5和str4同步修改

	int i = 0;
	int& i1 = i;//i是左值,i1是左值引用
	int&& i2 = 1;//1是右值,i2是右值引用
	int && i3 = s
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值