Re: Class Destructor doesn't destroy?
- From: "Alexander Nickolov" <agnickolov@xxxxxxxx>
- Date: Mon, 28 Jan 2008 13:19:33 -0800
Just for fun, here's an even more esoteric solution :)
char storage[sizeof(Numbers)];
Numbers* n2 = new(storage) Numbers(5, 6);
....
n2->~Numbers();
The above code allocates and subsequently constructs your
object on the stack, then destroys it when you are finished and
finally the memory is reclamed when storage goes out of scope.
Note that unlike automatic variables, the destructor won't be called
automatically.
Now, of course I won't actually recommend this kind of coding
style, but in rare specialized circumstances I've found the placement
new technique useful... (When writing a custom memory manager
to be more precise.)
--
=====================================
Alexander Nickolov
Microsoft MVP [VC], MCSD
email: agnickolov@xxxxxxxx
MVP VC FAQ: http://vcfaq.mvps.org
=====================================
"Gerry Hickman" <gerry666uk@xxxxxxxxxxxxxxxx> wrote in message
news:uER06v1XIHA.536@xxxxxxxxxxxxxxxxxxxxxxx
Hi,
If I instantiate a Class using operator new, I can destroy it with
operator delete, but if I instantiate it without operator new, I don't
seem to be able to destroy it until it goes out of scope - manually
calling the destructor doesn't completely destroy it.
In this function, the destructor gets called twice; once in-line, then
again when the function returns.
void classInstantiation() {
int a,b;
Numbers n2 = Numbers(5,6);
a = n2.Add();
wcout << a << endl; // prints 11
b = n2.Multiply();
wcout << b << endl; // prints 30
// Finished with numbers now
n2.~Numbers();
// Work with strings
// More processing here
}
--
Gerry Hickman (London UK)
.
- Follow-Ups:
- Re: Class Destructor doesn't destroy?
- From: Igor Tandetnik
- Re: Class Destructor doesn't destroy?
- References:
- Class Destructor doesn't destroy?
- From: Gerry Hickman
- Class Destructor doesn't destroy?
- Prev by Date: Re: Class methods changed from pointer (VS6) to reference (VS7)
- Next by Date: Re: Class Destructor doesn't destroy?
- Previous by thread: Re: Class Destructor doesn't destroy?
- Next by thread: Re: Class Destructor doesn't destroy?
- Index(es):
Relevant Pages
|