栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

lvalues and rvalues in C++

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

lvalues and rvalues in C++

lvalue & rvalue

参考链接:油管

lvalue: something always on the left side. lvalue always has some storage back in them.

rvalue: something always on the right side. tempoary variable, which doesn't have location.

You can only take a lvalue reference(one ampersand) from a left value, unless it is const.

You can only take a rvalue reference(two ampersands) from a right value.

#include 
#include 

using namespace std;
//rvalue reference
void printValue(string&& str)
{
    std::cout<<"Show string rvalue "< 
Move semantics 

Sometimes, it is unnecessary to copy the large data.

In the following code, if we use the copy constructor, the two objects would  be created and two memory allocation would happens.

We want just once!

So move instead of copy.

Firstly, define a basic string class

 and destructor and copy constructor

 

We just want a single memory allocation, so the resource intialized by the tempory variable would be moved to the final object instead of copy and destory. 

#include 
#include
using namespace std;

class String
{

	public:
	 String()=default;
	String(const char* string)
	{
		printf("Created!n");
		m_Size = strlen(string);
		m_Data = new char[m_Size + 1];
		memcpy(m_Data, string, m_Size);
	}

	String(const String& other)
	{
		printf("Copied!n");
		m_Size = other.m_Size;
		m_Data = new char[m_Size];
		memcpy(m_Data, other.m_Data, m_Size);
	}

	
	String(String&& other) noexcept
	{
		printf("Moved!n");
		m_Size = other.m_Size;
		m_Data = other.m_Data;
		other.m_Size = 0;
		other.m_Data = nullptr;
		//memcpy(m_Data, other.m_Data, m_Size);
	}
	~String()
	{
		delete m_Data;
		printf("Delete m_Data of Stringn");
	}

	void Print()
	{
		for (uint32_t i=0;i 

 

We want a single allocation!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/509993.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号