carlos lopez
carlos lopez

Reputation: 25

should a destructor be included with a pointer using automatic storage?

When I create a class, include a pointer in it, and create an object in automatic storage, should I include a destructor in the class? (is it necessary to free the space in the memory?) Example:

class Node{
    char *Name;
    int age;
    Node(char *n = 0, int a = 0) {
        name = strdup(n);
        age = a;
    }
    ~Node(){
        if (name != 0)
            delete(name);
    }
}

Node node1("Roger",20);

Upvotes: 1

Views: 129

Answers (3)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

is it necessary to free the space in the memory?

Yes, it's essential to avoid memory leaks.

Anyway you must use free(name); in your example, since strdup() is a pure C function, and uses the malloc() function to allocate the memory for the copy returned.


Also, you should avoid managing raw pointers yourself in C++. Either use smart pointers, or standard C++ containers, or for your specific case simply std::string.

Raw pointers don't go well with, respectively complicate, implementing the Rule of Three (5/zero).

If you have something allocated from a C-style interface, you can always use a smart pointer, and provide a custom deleter function, that actually uses the appropriate free() call.

Upvotes: 4

NathanOliver
NathanOliver

Reputation: 181027

If your class has a pointer that points to memory that is allocated with new \ new[] \ malloc() then you need to implement the Rule of Three

That said, instead of using a raw char * and manual memory management, use a std::string instead. you can still get a const char* out of it if you need it for other functions but it fully self managed container. With it you would not need to provide a copy constructor or destructor as the default ones provided by the compiler will work.

Upvotes: 2

HelloWorld
HelloWorld

Reputation: 1863

Yes, this is mandatory to avoid memory leaks. It doesn't matter if you are using a class or something else. It's important what strdup says. But you must not use delete, instead use free. The memory in strdup is created by using malloc, not new.

http://pubs.opengroup.org/onlinepubs/009695399/functions/strdup.html

strdup - duplicate a string

The returned pointer can be passed to free(). A null pointer is returned if the new string cannot be created.

P.S. Don't miss const in your declaration of char *n, otherwise the caller might expect the string is modified and a simple-string literal cannot be passed without a warning.

P.S.2: Prefer using nullptr instead of 0. This has been discussed several times on SO.

Upvotes: 1

Related Questions