我们可以通过这样做来引发失败:
struct mystruct
{
float x;
~mystruct() { x = 99; }
};
class cls
{
public:
mystruct* ptr;
void fun()
{
mystruct str = {10};
ptr = &str;
std::cout<<"bbq";
}
void fun2()
{
std::cout << ptr->x << std::endl;
}
};
...
obj.fun();
obj.fun2();
Now, it may happen that obj.fun2();
prints 99, or it may show some random other number, or it may crash. This is because the "use of an object that has been destroyed is undefined behaviour" - undefined behaviour means that the C++ standard does not define what happens, and "anything could happen", including crashing or hanging, or it works "as you expect". But the object will be destroyed. Since the original code doesn't actually USE ptr
after the object it points to was destroyed, nothing bad happens (in fact, it's not even undefined behaviour in the example code - it is only undefined to "use pointed at object after the object has been destroyed").
Edit:
this code, however:
mystruct* ptr = new mystruct;
fun(ptr);
std::cout<<"bbq";
causes a memory leak, since ptr
is never deleted (and if fun
where to actually modify ptr
outside of the function itself, e.g by using mystruct *&ptr
as the argument, then you would have a memory block for mystruct
that is no longer referenced, which is an even worse memory leak - and of course a value in ptr
that points to destroyed object, so you can't use ptr
anyway)