Вопрос

I was wondering if I have to delete this pointer in example like this :

class Person
{
  public:
    Person(char *name) :_name(name) {}

    // Is this delete necessary?
    ~Person() {
        cout<<"Godbay Person"<<endl;
        delete _name;
    }

  private:
    char * _name;
}
Это было полезно?

Решение

This is pretty surely wrong in any case.

There are two possibilities:

  1. The name is created on the free store exclusively for your object, and your object has to assume ownership. Then the name has to be deleted.

  2. The name is not created on the free store (e.g. as a string litaral, which is quite possible), or some other object is managing the name, so your object should not assume ownership. Then any deletion would wreak havoc with your program.

So why do I say its wrong even in the first case? Because name sounds like a string, not a single character, wich means name* will point to an dynamically alocated array of characters. In that case, the correct way to delete it would be delete[] name.

But: If possible, avoid using plain (char) pointers, for case 1. Use some memory management class instead (a string class or smartpointers), to get rid of the headaches of manually managing memory ownership. delete and delete[] should appear only seldom in your code except if you don't have access to up-to-date C++ compilers.

Другие советы

It is a matter of who owns the allocated memory, in this case it looks like Person is not owning it so then no, so there is no need to delete. Using raw pointers like you do in Person always give rise to questions about ownership, that is why it is recommended to use shared_ptr/unique_ptr instead or even better std::string since it seems to be a string.

Generally, you have to call delete each time you create a pointer with new.

It depends on creation procedure.

In this case no:

Person *p = new Person("John");

In this case yes:

char *str = new char[32];
::strcpy(str, "John");
Person *p = new Person(str);

In this case yes, but with ::free function rather than operator delete.

char *str = (char *)::malloc(32);
::strcpy(str, "John");
Person *p = new Person(str);

Consider using std::string instead of C string pointer.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top