Hi i have few doubt related to heap variable…
I want to write a function as below ->
struct test
{
int x;
int y;
};
test* fun()
{
test *ptr = new test;
return ptr;
}
-
My doubt is returning a heap variable once it will go out of scope it will lost its value.
-
There is definitely a memory leak.(As heap variable is not deleted.)
So how can i design such kind of function.
Dynamically allocated objects (what you call heap variables) do not get destroyed at the end of the scope in which they were created. That’s the whole point of dynamic allocation. While the
testobject is dynamically allocated, the pointerptris not – it will be destroyed when it goes out of scope. But that’s okay! You copy the value of the pointer out of the function and this copy still points at thetestobject. Thetestobject is still there. The function you’ve written is fine, but it isn’t exactly good style.Yes, there is a memory leak if nobody ever does
deleteon a pointer to thetestobject you created. That’s a problem with returning raw pointers like this. You have to trust the caller todeletethe object you’re creating:A common C-style way of doing this (which is definitely not recommended in C++) is to have a
create_testanddestroy_testpair of functions. This still puts the same responsibility on the caller:The best way to get around this is to not use dynamic allocation. Just create a
testobject on the stack and copy it (or move it) out of the function:If you need dynamic allocation, then you should use a smart pointer. Specifically, the
unique_ptrtype is what you want here:The calling function can then handle the
unique_ptrwithout having to worry about doingdeleteon it. When theunique_ptrgoes out of scope, it will automaticallydeletethetestobject you created. The caller can however pass it elsewhere if it wants some other function to have the object.