Problems with destructor

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • m013690
    New Member
    • Sep 2006
    • 23

    Problems with destructor

    Hi all,

    I'm having a problem with a program that continually generates assertion errors. After stepping through in the debugger and inserting several lines to track the progress, I've found it is attempting to call the class destructor 2 times more than it calls the class constructor. As a result, it's trying to delete[] memory that has never been allocated, and causing a problem.

    I can make the problem go away by simply removing the delete[] statement from the destructor, but I know that's not right.

    It's a textbook project on overloading operators, and I'm wondering if it's something to do with implicitly created temporary objects, but I would think the compiler would have to call the constructors when it created those temporary objects. It's not. I've basically copied the code directly out of the textbook, though changed the operations and types of course to suit the assignment, but the definitions and syntax is identical. All I changed was the meat of the functions, and that's not what's causing the problems.

    I can post code if desired, but it's not short...
  • m013690
    New Member
    • Sep 2006
    • 23

    #2
    Never mind, I've got it figured out now. 'Twas a problem with a copy constructor... Guess I'm still learning.

    What was happening (or so I believe I've discovered) was that the default copy constructor was copying over dynamically allocated memory pointers, so when the destructor was called it was releasing memory which was still being used by another object. I had to actually define a copy constructor instead of allowing the compiler to do it, since there was dynamically allocated memory involved (new [ ] operator). Any experts want to confirm for me that I've learned the proper lesson here?

    Comment

    • Banfa
      Recognized Expert Expert
      • Feb 2006
      • 9067

      #3
      Yes that sounds about right, for any class where 1 or more of the members is a pointer that you allocate memory to using new or malloc then if you use the default copy constructor you will get memory errors on class destruction.

      This is because the default copy constructor just copies the members from 1 class to another but if some of the members are pointers to allocated memory what you need to do is allocate memory for the second class (the one being copied to ) and copy the contents of the memory.

      Comment

      Working...