Why is my destructor being called and how can I fix it

This question already has an answer here:

  • What is The Rule of Three? 8 answers

  • When you do this

    foo=creature(choice);
    

    a temporary creature object is created on the RHS of the assignment. Its destructor is called once the statement is done, ie at end of the line.

    There isn't really anything to fix, but you can initialize foo after reading in choice , rather than default initializing and then assigning:

    int choice;
    
    cout<<"enter 1 2 or 3 to choose ur monster"<<endl;
    cin>>choice;
    
    creature foo(choice);
    

    As juanchopanza pointed out in his answer, the line

    foo = creature(choice);
    

    creates a temporary creature object before assigning it to foo. If you don't want this to happen, create it with

    creature foo(choice);
    

    To add to the other answers, your question referred to "fixing the destructor". There is nothing to fix, however there may be a bug in what you're trying to accomplish due to the destructor being invoked.

    What will happen with your current code is that temporary copies may be created without you tracking them. When their destructor is called, you will decrement the count variable inadvertently, possibly giving you a negative value for count .

    If you want the object static count member variable to correctly reflect the number of objects created and destroyed, your class is missing a user defined copy constructor to track the number of instances.

    You need to add this function.

    class creature{
    public:
        creature(const creature& c) : 
             name(c.name), happy_level(c.happy_level) { ++count; }
    };
    

    This function will be called when you make copies or assign.

    Live Examples:

    (original code): http://coliru.stacked-crooked.com/a/ea9821e622aa4cdc

    (changed code): http://coliru.stacked-crooked.com/a/b774a896377bdf97

    The only difference is that the original code has the copy constructor commented out, while the changed code has the copy constructor intact.

    Note that in the original code, I wanted to know how many objects are created and destroyed, but I got back a result of -1 when the final object was destroyed. This is not correct as obviously the result should yield 0, meaning all creatures are destroyed.

    The changed code shows the correct number, and that is because the object creation of the temporary creature was taken into account.

    链接地址: http://www.djcxy.com/p/73180.html

    上一篇: 双重免费或腐败(如果重新排序,则运行正常)

    下一篇: 为什么我的析构函数被调用,我该如何解决它