Imagine the following class:
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 } {} }
I am a bit confused about the implementation of the destructor for MyString
. My first thought was that it would look like this:
~MyString() { delete [] str; }
But how can I remove str if I cannot be sure that it was highlighted? For example, I could create an instance of MyString
as follows:
const char* c_string = "Hello, World!"; MyString my_string(c_string, 13);
In this case, I should not delete str
because it was not declared on the heap, but if I created an instance of MyString
as follows:
char* char_array = new char[13]{'H','e','l','l','o',',',' ','W','o','r','l','d','!'}; MyString my_string(char_array, 13);
not deleting str
will result in a memory leak (I assume) because it will be declared on the heap. But if I created an instance of MyString
as follows:
char* char_array = new char[13]{'H','e','l','l','o',',',' ','W','o','r','l','d','!'}; MyString my_string(char_array + 3, 10);
I should not delete str
, because although it is on the heap, it was not allocated; he simply points to a part of something else that has been highlighted.
So, how can I be sure that I am not deleting what I should not delete or not deleting, what needs to be deleted? Would the answer be different if MyString used char*
instead of const char*
s? What if I used MyString my_string = new MyString...
?
Edit: To clarify, I didn't actually write a string class. I use a char array as an array of bytes. I assume that std :: string will not work, since bytes can be 0.