Double Frees in Modern C++

Modern C++ solves this differently:

  1. std::string s1 = "Cpp";
  2. std::string s2 = s1; // Duplicate the data in s1.
  • The heap data from s1 is duplicated and s2 gets its own independent copy.
  • When s1 and s2 go out of scope, they each free their own memory.

Before copy-assignment:

10.2.1. Double Frees in Modern C++ - 图1

After copy-assignment:

10.2.1. Double Frees in Modern C++ - 图2