Thursday 15 July 2010

c++ - Is the pointer to data on the heap deleted when it goes out of scope? -



c++ - Is the pointer to data on the heap deleted when it goes out of scope? -

i have heard anonymous temporary allocated on stack , gets destroyed @ end of evaluation of containing expression.

so if have following:

//a function defined int foo(int* p) { ... // writing explicitly avoid confusion question delete p; } int main() { foo(new int); // anonymous pointer? homecoming 0; }

now when foo called main(), anonymous pointer heap element copied p, means there 2 pointers same heap element. if end using delete in foo delete info , set pointer nullptr, still left anonymous pointer pointing garbage. anonymous pointers cleared when goes out of scope?

the situation similar using shared_ptr's constructor form takes raw anonymous pointer caller info build shared pointer pointer value copied constructor. such anonymous pointers set null when go out of scope?

i think smell misconception in question. however, might wrong that; if disregard.

you inquire this:

even if end using delete in foo delete info , set pointer nullptr, still left anonymous pointer pointing garbage. anonymous pointers cleared when goes out of scope?

the situation similar using shared_ptr's constructor form takes raw anonymous pointer caller info build shared pointer pointer value copied constructor. such anonymous pointers set null when go out of scope?

from questions, seems might under impression setting pointer null ("clearing" it) essential part of freeing whatever points to. in c++, not case. free object p points to, delete p;, end of story. may p = nullptr; afterwards if want ensure looks @ p later realizes it's invalid, whether or not, object pointed before gone.

so in hypothetical code:

int foo(int* p) { //some content delete p; } int main() { foo(new int); // anonymous pointer? }

no memory leaked, , fine. question of whether temporary, anonymous pointer passed foo referencing garbage after foo returns meaningless, since temporary invisible @ point , not farther participate in programme (raw pointers don't have destructors).

but in this hypothetical code:

int foo(int* p) { //some content, no delete p } int main() { foo(new int); // anonymous pointer? }

nothing delete anonymous new int, have memory leak.

c++

No comments:

Post a Comment