So I have been working with c++ and pointers for a year and a half now, and i thought i had them succeed. I have called delete on objects many times before and the objects actually got deleted, or at least i thought they did.
The code below is just confusing the hell out of me:
#include <iostream>
class MyClass
{
public:
int a;
MyClass() : a(10) {
std::cout << "constructor ran
";
}
void method(std::string input_) {
std::cout << param_ << "
";
}
~MyClass() {
std::cout << "destructor ran
";
}
};
int main()
{
MyClass* ptr = new MyClass;
ptr->method("1");
delete ptr;
ptr->method("2.5");
}
this code outputs:
constructor ran
1
destructor ran
2.5
I was confused as to why it was not throwing an error of any sort - I was expecting a memory out of bounds exception or alike, but nothing. The for
loop was in there incase there was some sort of hidden garbage collection, even though as far as I know there is no garbage collection in c++.
Can anyone explain as to why this code works, or where I am going wrong with this code for it not to give me the error?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…