Sometimes, it is desired to track the number of objects created on the heap by a particular class. Suppose class A_outer has a nested class A_inner. A_outer creates objects of A_inner on the heap. Is it possible to track how many A_inner objects were created by an instance of A_outer using a static member in A_inner?
It is tempting to think that the static member in the A_inner class "belongs" to an instance of A_outer, as follows:
instance1 of A_outer
-instance1 of A_inner
-instance2 of A_inner
-static member Count of A_inner "in instance1 of A_outer" = 2
instance2 of A_outer
-instance1 of A_inner
-instance2 of A_inner
-instance3 of A_inner
-static member Count of A_inner "in instance2 of A_outer" = 3
Unfortunately, the A_inner class is actually a class just like any other, and so there is only ONE value of the static member. Thus, by the time instance3 of A_inner was created, the value of Count would have been 5!
In fact, an easy way to remember this is to look at the initialization of the static member:
int A_outer::A_inner::Count = 0;
which does not distinguish which instance (of A_outer) it is referring to (or whether one even exists in the first place).
P.S. How should the counting be accomplished, then? One obvious way is to use a member in A_outer. To address the concern of "forgetting to increase the count", consider using a method Create_A_inner to create the inner instance and increase the count.
Labels
algorithm
allegro
anime
api
arcade
asdf
blender
books
boost
bootstrap
c
c++
CLR
cmake
cmd
common lisp
concepts
css
detective
emacs
free
games
graphical programming
graphics
gui
haskell
html
hyper-v
interpersonal skills
jade
jam
java
javascript
jni
jpostal
leadership
libpostal
library
linux
lsp
lsp-mode
management
maths
mingw
msvc
msys2
music
network
oop
open source
party games
phaser
postgresql
programming
promote
puzzle
quickfix
recommended
recorder
reference
review
sdl2
self-help
setup
sheet music
slime
team building
tidbits
tools
travel
tutorial
typescript
unity
vb
vm
web pages
winapi
windows
windows 7
windows 8.1
No comments:
Post a Comment