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'm a bit confused about implementing a destructor for MyString
. My first thought was that it would look like this:
~MyString() {
delete [] str;
}
But how can I delete str if I can't be sure that it was allocated? For example, I could create an instance of MyString
like this:
const char* c_string = "Hello, World!";
MyString my_string(c_string, 13);
in which case I shouldn't delete str
because it was not declared on the heap, but if I created an instance of MyString
like this:
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
would cause a memory leak (I assume) because it would be declared on the heap. But if I created an instance of MyString
like this:
char* char_array = new char[13]{'H','e','l','l','o',',',' ','W','o','r','l','d','!'};
MyString my_string(char_array + 3, 10);
I shouldn't delete str
because although it's on the heap, it hasn't been allocated; it just points to part of something else that's been allocated.
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 char*
s instead of const char*
s? What if I used MyString my_string = new MyString...
?
Aucun commentaire:
Enregistrer un commentaire