Re: Is it *legal* (as opposed to sensible) to explicitly destruct
an object and deallocate the memory?
On 12/12/2010 16:48, Stuart Golodetz wrote:
On 12/12/2010 16:28, ?? Tiib wrote:
On Dec 12, 5:51 pm, Stuart Golodetz<b...@blah.com> wrote:
Hi all,
Just feeling curious -- I know the following is ill-advised, but is it
actually formally illegal?
#include<iostream>
struct X
{
~X()
{
std::cout<< "~X()\n";
}
};
int main()
{
X *x = new X;
//delete x;
x->~X();
::operator delete(x);
return 0;
}
It would certainly be legal in the context of *placement* new, but is
there a requirement in the standard that all "new"s are matched by
"delete"s, rather than "operator delete"s?
It feels legal. It is doing all same things in same order what simple
'delete x;' is doing by standard.
Thanks -- I think I'd expect it to work, just curious because it's the
sort of thing that might be formally undefined for some reason that I
haven't come across.
Stu
The following might be a consideration:
struct foo
{
foo()
{
std::cout << "foo ctor called\n";
}
~foo()
{
std::cout << "foo dtor called\n";
}
void* operator new(std::size_t aSize)
{
std::cout << "overloaded operator new called\n";
return ::operator new(aSize);
}
void operator delete(void* p)
{
std::cout << "overloaded operator delete called\n";
return ::operator delete(p);
}
};
int main()
{
foo *x = new foo;
delete x;
//x->~foo();
//::operator delete(x);
foo *y = new foo;
//delete y;
y->~foo();
::operator delete(y);
return 0;
}
outputs:
overloaded operator new called
foo ctor called
foo dtor called
overloaded operator delete called
overloaded operator new called
foo ctor called
foo dtor called
/Leigh