Deallocating my constructor memory
Apr 24, 2012 at 12:50am UTC
So I have the following in my constructor:
1 2 3
Queue<T> *newQueue = new Queue<T>;
...// do stuff not involving newQueue
items[i] = newQueue;
Now I need to deallocate the memory I used in my constructor so I try the following in my destructor:
delete newQueue;
But the compiler is yelling at me saying:
1 2
Error 8 error C2065: 'newQueue' : undeclared identifier
Error 9 error C2541: 'delete' : cannot delete objects that are not pointers
What is suppose to go in my destructor?
Apr 24, 2012 at 3:23am UTC
I assume
items
is some kind of container that is owned by the class. In which case (and assuming all of its elements were added this way) you would iterate through
items
and delete each member.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
class MyClass
{
std::vector<Foo*> stuff;
MyClass()
{
stuff.push_back( new Foo );
// ..or..
Foo* f = new Foo;
stuff.push_back( f );
}
~MyClass()
{
while ( !stuff.empty() )
{
delete stuff.back();
stuff.pop_back();
}
}
};
Topic archived. No new replies allowed.