-2

From: https://stackoverflow.com/a/3109981/462608

string(string&& that)   // string&& is an rvalue reference to a string
{
    data = that.data;
    that.data = nullptr;
}

What have we done here? Instead of deeply copying the heap data, we have just copied the pointer and then set the original pointer to null (to prevent 'delete[]' from source object's destructor from releasing our 'just stolen data'). In effect, we have "stolen" the data that originally belonged to the source string.

Please explain the line in bold from the above quote.

that is a rvalue so how would it be deleted from source object's destructor? Please give examples.

Aquarius_Girl
  • 21,790
  • 65
  • 230
  • 411
  • Without `that.data = nullptr`, when `that` destructed, it would release `that.data` aka `this->data` because of `data = that.data;`. "Source" in the link means `that`. – Louis Go Aug 31 '20 at 07:08
  • @LouisGo Request: Write an answer. – Aquarius_Girl Aug 31 '20 at 07:10
  • This function is missing the first line - it should `delete [] this->data;` otherwise previously allocated array will leak. – user7860670 Aug 31 '20 at 07:10
  • @user7860670 Please write an answer. – Aquarius_Girl Aug 31 '20 at 07:11
  • 3
    @user7860670 This seems to be a constructor, which means there's no previously allocated array. – Some programmer dude Aug 31 '20 at 07:11
  • It's a move constructor, so `that` is the "source object", `*this` is the destination. – molbdnilo Aug 31 '20 at 07:11
  • The term "just stolen data" refers to the fact that `*this` (the object being constructed) has silently taken ownership of `that.data` (the data owned and managed by the object `that`). The assignment `data = that.data;` causes the object being constructed (`*this`) and the object being moved from (`that`) to have the same value of `data`. Hence two objects now contain the same pointer. If those objects are both destroyed, that `data` will be released twice by the destructor - giving undefined behaviour. The assignment `that.data = nullptr` causes `that` to no longer own the data. – Peter Aug 31 '20 at 08:39
  • Why not just `std::swap(data, that.data);` and let `that`'s destructor take care of `that.data` which it had just acquired via swap? – Eljay Aug 31 '20 at 12:24

2 Answers2

2

The wording might be a little misleading.

The "source" mentioned is the "source object", i.e. the object that is referred to by that.

It might be easier to understand if you see something like

// Need std::move to turn source_object into an rvalue reference
string destination_object(std::move(source_object));
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

Take the snippet before the quote. You may know string would delete[] data when it destructs.

~string()
{
    delete[] data;
}

Without that.data = nullptr, when that destructed, it would release that.data aka this->data because of data = that.data;.

"Source" in the link means that.

Louis Go
  • 2,213
  • 2
  • 16
  • 29