title: How can I know if I need to delete something in C++?
body: <p>Imagine the following class:</p>
  
  <pre><code>class MyString {
  public:
      const char* str;
      std::size_t str_len;
  
      MyString(const char* str, std::size_t str_len)
          : str { str }
          , str_len { str_len }
      {}
  }
  </code></pre>
  
  <p>I'm a bit confused about implementing a destructor for <code>MyString</code>. My first thought was that it would look like this:</p>
  
  <pre><code>~MyString() {
      delete [] str;
  }
  </code></pre>
  
  <p>But how can I delete str if I can't be sure that it was allocated? For example, I could create an instance of <code>MyString</code> like this:</p>
  
  <pre><code>const char* c_string = "Hello, World!";
  MyString my_string(c_string, 13);
  </code></pre>
  
  <p>in which case I <em>shouldn't</em> delete <code>str</code> because it was not declared on the heap, but if I created an instance of <code>MyString</code> like this:</p>
  
  <pre><code>char* char_array = new char[13]{'H','e','l','l','o',',',' ','W','o','r','l','d','!'};
  MyString my_string(char_array, 13);
  </code></pre>
  
  <p>not deleting <code>str</code> would cause a memory leak (I assume) because it would be declared on the heap. But if I created an instance of <code>MyString</code> like <em>this:</em></p>
  
  <pre><code>char* char_array = new char[13]{'H','e','l','l','o',',',' ','W','o','r','l','d','!'};
  MyString my_string(char_array + 3, 10);
  </code></pre>
  
  <p>I <em>shouldn't</em> delete <code>str</code> because although it's on the heap, it hasn't been allocated; it just points to part of something else that's been allocated.</p>
  
  <p>So how can I be sure that I'm not deleting something that I shouldn't be deleting or failing to delete something that needs to be deleted? Would the answer be different if MyString used <code>char*</code>s instead of <code>const char*</code>s? What if I used <code>MyString my_string = new MyString...</code>?</p>
  
  <p><strong>Edit:</strong> To clarify, I'm not actually writing a string class. I'm using a char array as a byte array. I assume std::string wouldn't work, since the bytes could be 0.</p>