Skip to main content
gamedev.net
🔒 Locked

Basic Constructors and Destructors question (C++)

Started by dc443 4 replies 800+ views
Original Post
dc443
dc443
If I have a class, and I have this in the source file with the ctor and dtors:
static int count = 0;
and then in all constructors I put this:
count++; printf("count: %d, location: %p\n",count,this); 
and in destructor:
count--; printf("count: %d, location: %p\n",count,this); 
Then at the end of normal program execution the value in count should always be zero, right? There should never be destructors called for which a constructor was never called. Such is not the case. I end up with count being a negative number and I have it calling the destructor on objects that were never constructed. Could the C++ STL be responsible for this? I have vectors that hold my objects.
SiCrane
SiCrane
Did you put the count increment inside the copy constructors? If you don't write the copy constructor, the compiler will generate one for you automatically.
dc443
dc443
Yep you got it. That was the problem. Thanks!!
iMalc
iMalc
Also beware of the static initialisation order problem. Some global objects might be initialised before count is, again causing the same result.
SiCrane
SiCrane
No, that can't happen with a static int initialized to 0.
iMalc
iMalc
Quote:
Original post by SiCrane
No, that can't happen with a static int initialized to 0.
Ah you're right, my web searches confirm that it would only be a problem if the static int was initialised with a non-compile-time expression. Other than that, built-in types are unaffected.
Handy to know such things anyway.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.