参考链接:油管
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!



