
Using TScopedPointer to track an object
A scoped pointer is a pointer that is auto-deleted at the end of the block in which it was declared. Recall that a scope is just a section of code during which a variable is "alive". A scope will last until the first closing brace, }
, that occurs.
For example, in the following block, we have two scopes. The outer scope declares an integer variable x
(valid for the entire outer block), while the inner scope declares an integer variable y
(valid for the inner block, after the line on which it is declared):
{ int x; { int y; } // scope of y ends } // scope of x ends
Getting ready
Scoped pointers are useful when it is important that a reference-counted object (which is in danger of going out of scope) is retained for the duration of usage.
How to do it...
To declare a scoped pointer, we simply use the following syntax:
TScopedPointer<AWarrior> warrior(this );
This declares a scoped pointer referencing an object of the type declared within the angle brackets: < AWarrior >
.
How it works…
The TScopedPointer
variable type automatically adds a reference count to the variable pointed to. This prevents deallocation of the underlying object for at least the life of the scoped pointer.