c++ - Locally declared object's internal memory intact outside scope? -
the function f1
creates instance of foo
, sets foo.ptr[0] = 2
.
#include <iostream> using namespace std; class foo { public: int *ptr; inline foo(int a) { ptr = new int[a]; } inline ~foo() { delete[] ptr; } }; foo f1() { foo a(5); a.ptr[0] = 2; return a; } int main() { foo = f1(); cout<<a.ptr[0]<<endl; return 0; }
what expected output: junk value.
f1
returns by value, means copy of a
made , copy shares same memory locations @ (a
, it's copy) respective ptr
s point at.
outside f1
, a
gets destroyed. it's destructor called deallocate ptr
's memory. means memory location copy's ptr
points @ invalid. so, expect junk value output.
the output 2
.
why?
the standard never says should expect "junk value". instead, says you'll undefined behaviour. since not following rule of 3 (or five), dynamically allocated array of int
s destroyed when f1
returns , object a
ends pointer destroyed array. access gives undefined behaviour.
the reason you're seeing value 2
because memory location hasn't been reused since value 2 in there. however, reasoning meaningless far standard concerned.
Comments
Post a Comment