By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,305 Members | 1,619 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,305 IT Pros & Developers. It's quick & easy.

Problems with destructor

P: 23
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...
Sep 30 '06 #1
Share this Question
Share on Google+
2 Replies


P: 23
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?
Sep 30 '06 #2

Banfa
Expert Mod 5K+
P: 8,916
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.
Sep 30 '06 #3

Post your reply

Sign in to post your reply or Sign up for a free account.