dynamic_cast<T*>(deleted_pointer)?

S

Steven T. Hatton

The result shown below doesn't surprise me now. But it did several months
ago when I followed some bad advice and tried to check if I had a live
object at the address referenced by a pointer. Can I assume the result is
consistente with the Standard?

Tue May 10 21:24:24:> cat foo.cc
#include <iostream>
struct Foo{virtual ~Foo(){} };
struct Bar{virtual ~Bar(){} };
int main(){
Foo* foo = new Foo;
Bar* bar = new Bar;

std::cout << "dynamic_cast<Foo*>(foo)"
<< dynamic_cast<Foo*>(foo)
<< std::endl;

delete foo;
std::cout << "dynamic_cast<Foo*>(foo)"
<< dynamic_cast<Foo*>(foo)
<< std::endl;

std::cout << "dynamic_cast<Foo*>(bar)"
<< dynamic_cast<Foo*>(bar)
<< std::endl;
}

Tue May 10 21:25:45:> ./foo
dynamic_cast<Foo*>(foo)0x804a008
dynamic_cast<Foo*>(foo)0x804a008
dynamic_cast<Foo*>(bar)0

--
"If our hypothesis is about anything and not about some one or more
particular things, then our deductions constitute mathematics. Thus
mathematics may be defined as the subject in which we never know what we
are talking about, nor whether what we are saying is true." - Bertrand
Russell
 
D

David White

Steven T. Hatton said:
The result shown below doesn't surprise me now. But it did several months
ago when I followed some bad advice and tried to check if I had a live
object at the address referenced by a pointer. Can I assume the result is
consistente with the Standard?

Tue May 10 21:24:24:> cat foo.cc
#include <iostream>
struct Foo{virtual ~Foo(){} };
struct Bar{virtual ~Bar(){} };
int main(){
Foo* foo = new Foo;
Bar* bar = new Bar;

std::cout << "dynamic_cast<Foo*>(foo)"
<< dynamic_cast<Foo*>(foo)
<< std::endl;

delete foo;

All bets are off once you delete it.
std::cout << "dynamic_cast<Foo*>(foo)"
<< dynamic_cast<Foo*>(foo)
<< std::endl;

Anything can happen above - the "right" answer, the "wrong" answer, a crash,
a nuclear explosion, or anything else.
std::cout << "dynamic_cast<Foo*>(bar)"
<< dynamic_cast<Foo*>(bar)
<< std::endl;
}

Tue May 10 21:25:45:> ./foo
dynamic_cast<Foo*>(foo)0x804a008
dynamic_cast<Foo*>(foo)0x804a008

Probably the deleted memory still hasn't been altered following the delete.
But you can't count on that.
dynamic_cast<Foo*>(bar)0

DW
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,264
Latest member
FletcherDa

Latest Threads

Top