简体   繁体   中英

How to debug destruct function in Cpp program

Code

I am trying to debug below code:

#include <iostream>

class wine
{
public:
    //wines name/brand
    char *name;
    //wines age
    int age;
    //in liters
    long double volume;
    //def construct
    wine();
    //construct
    wine(char *name, int age, long double volume) : name(name), age(age), volume(volume) {};
    //destruckt
    ~wine();
};

wine::wine() {}
wine::~wine() 
{
    delete &name;
    delete &age;
    delete &volume;
}

int main()
{
    char a[5] = { 'G','a','l','l','o' };
    wine old(a, 50, 1);
    for(int i = 0; i < 5; i++)
    {
        std::cout << a[i];
    }
    while (!std::cin.ignore());
    delete &old;
    return 1;
}

What I have observed while debugging is that the destruct function is the error but I have not achieved anything else

You don't do any dynamic memory allocation with new , so you need no delete either. Remove the delete &old; . The destructor will automatically be called when old goes out of scope (which is at the end of your main function).

well what i have observed while debugin is that the destruct function is the error

That's right. Your wine class contains nothing that is dynamically allocated and therefore nothing that needs to be deleted using delete . Yet your destructor tries to delete its member variables.

Remove those delete calls in the destructor. You can just get rid of the destructor as a whole if you want (this way wine is left with a default destructor that does nothing special).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM