I am looking at this answer showing a move constructor:
https://stackoverflow.com/a/3109981/997112
#include <cstring>
#include <algorithm>
class string
{
char* data;
public:
string(const char* p)
{
size_t size = strlen(p) + 1;
data = new char[size];
memcpy(data, p, size);
}
~string()
{
delete[] data;
}
string(const string& that)
{
size_t size = strlen(that.data) + 1;
data = new char[size];
memcpy(data, that.data, size);
}
};
and then a move constructor is introduced:
string(string&& that) // string&& is an rvalue reference to a string
{
data = that.data;
that.data = 0;
}
If we assign pointer data
to the value that.data
, surely this causes a memory leak for the new char[size]
memory which data
was originally pointing to? I am confused.