C++ move assignment operator

Poby’s Home
2 min readFeb 22, 2021

--

All for efficiency. C++11

#include <iostream>
#include <cstdint>
#include <cstring>
#include <memory>
class String
{
private:
char *mData;
uint32_t mSize;
public:
// default constructor.
// could have used `String() = default`, but for printing.
String()
{
printf("default constructor");
}
// constructor that are useful for this application
String(const char *str)
{
printf("created: ");
mSize = strlen(str);
mData = new char[mSize];
memcpy(mData, str, mSize);
print();
}
// copy constructor
String(const String &other)
{
printf("copied: ");
mSize = other.mSize;
mData = new char[mSize];
memcpy(mData, other.mData, mSize);
print();
}
// move constructor
String(String &&other)
{
printf("moved: ");
mSize = other.mSize;
mData = other.mData;
other.mSize = 0;
other.mData = nullptr;
print();
}
// move assignment operator
String &operator=(String &&other)
{
printf("move assigned: ");
if (this != &other)
{
// if missing this, mData of original will be dangling
delete[] mData;
mSize = other.mSize;
mData = other.mData;
other.mSize = 0;
other.mData = nullptr;
print();
}
return *this;
}
~String()
{
printf("destrying...");
print();
delete[] mData;
}
int size()
{
return mSize;
}
void print()
{
for (int i = 0; i < mSize; i++)
{
printf("%c", mData[i]);
}
printf("\n");
}
};
int main()
{
String src = "Hello";
String desc(std::move(src)); // move constructor will be called
String src2 = "World";
String desc2(std::move(src2)); // move constructor will be called
String src3 = "!";
// move constructor will be called.
// This is not assignment. This is a construction!!
String desc3 = std::move(src3);
desc.print();
desc2.print();
desc3.print();
// assignment happens only when you assign to an existing variable
desc3 = std::move("Again!");
desc3.print();
}

--

--

No responses yet