c++ - Delete calling destructor but not deleting object? -
so have been working c++ , pointers year , half now, , thought had them succeed. have called delete on objects many times before , objects got deleted, or @ least thought did.
the code below confusing hell out of me:
#include <iostream> class myclass { public: int a; myclass() : a(10) { std::cout << "constructor ran\n"; } void method(std::string input_) { std::cout << param_ << "\n"; } ~myclass() { std::cout << "destructor ran\n"; } }; 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 confused why not throwing error of sort - expecting memory out of bounds exception or alike, nothing. for
loop in there incase there sort of hidden garbage collection, though far know there no garbage collection in c++.
can explain why code works, or going wrong code not give me error?
you're misunderstanding delete
does. delete
call destructor, , tell allocator that memory free. doesn't change actual pointer. beyond undefined.
in case, nothing actual data pointed to. pointer points same data pointed before, , calling methods on works fine. however, behavior not guaranteed; in fact, it's explicitly unspecified. delete
0 out data; or allocator allocate same memory else, or compiler refuse compile this.
c++ allows many unsafe things, in interest of performance. 1 of them. if want avoid kind of mistake, it's idea do:
delete ptr; ptr = null;
to ensure don't try reuse pointer, , crash if rather having undefined behavior.
Comments
Post a Comment