Re: Avoiding Dynamic Allocation
Thanks to all of your replies, that really helpful.
About the destructors, this may be a silly question. In the destructor can we use "delete" on any variables or do they have to be pointers? Because I've mostly seen code like:
Code:
AClass *ptr;
...
~AClass() { delete ptr; }
Can we delete ordinary variables as well?
Code:
AClass *ptr;
string name;
int number =10;
...
~AClass() { delete ptr; delete name; delete number;
}
Thank you very much
John
Re: Avoiding Dynamic Allocation
Quote:
Originally Posted by JohnSmith70
Thanks to all of your replies, that really helpful.
About the destructors, this may be a silly question. In the destructor can we use "delete" on any variables or do they have to be pointers? Because I've mostly seen code like:
Code:
AClass *ptr;
...
~AClass() { delete ptr; }
Can we delete ordinary variables as well?
Code:
AClass *ptr;
string name;
int number =10;
...
~AClass() { delete ptr; delete name; delete number;
}
Thank you very much
John
You only delete what you allocate. (HEAP variables)
The other variables are on the stack and are removed as the fall out of scope.
Re: Avoiding Dynamic Allocation
An example:
Code:
int main(int argc, char** argv)
{
//The following are pushed onto the stack as
//they come in to scope (automatically)
int mynum = 0; //Stack
char myarray[128] = {0}; //Stack
char* pHeap = 0; //Stack
//The following is put into heap memory as it is requested
pHeap = new char[256];
//delete / release memory
delete[] pHeap;
}
At the closing brace, the stack variables are automatically popped from the stack (removed from memory) as they fall out of scope.
The memory pointed to by pHeap is only released when you call delete for it.
Re: Avoiding Dynamic Allocation
Code:
AClass *ptr;
string name;
int number =10;
...
~AClass() { delete ptr; delete name; delete number;
}
The compiler itself will not allow to 'delete' non-pointers! ;)