0

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.

Community
  • 1
  • 1
user997112
  • 29,025
  • 43
  • 182
  • 361

1 Answers1

5

data isn't already pointing at anything because this is the constructor. This is the first thing that happens when the object is created.

When constructing this object, it takes ownership of that.data which was allocated by the other object. By assigning 0 to that.data, it ensures that the other object won't delete the data. Now this object is responsible for doing it, which it will do in its destructor.

Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
  • 1
    True, which is why the conventional syntax would be `string(string&& that) : data(that.data)` (initializer list). – MSalters Jun 30 '14 at 16:18