Creating variable on heap and return the same variable

c++, heap-memory

Solution

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 `test` object is dynamically allocated, the pointer `ptr` is 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 the `test` object. The `test` object 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 `delete` on a pointer to the `test` object you created. That's a problem with returning raw pointers like this. You have to trust the caller to `delete` the object you're creating:

void caller()
{
  test* p = fun();
  // Caller must remember to do this:
  delete p;
}

A common C-style way of doing this (which is definitely not recommended in C++) is to have a `create_test` and `destroy_test` pair of functions. This still puts the same responsibility on the caller:

void caller()
{
  test* p = create_test();
  // Caller must remember to do this:
  destroy_test(p);
}

The best way to get around this is to not use dynamic allocation. Just create a `test` object on the stack and copy it (or move it) out of the function:

test fun()
{
    test t;
    return t;
}

If you need dynamic allocation, then you should use a smart pointer. Specifically, the `unique_ptr` type is what you want here:

std::unique_ptr<test> fun()
{
    return std::unique_ptr<test>(new test());
}

The calling function can then handle the `unique_ptr` without having to worry about doing `delete` on it. When the `unique_ptr` goes out of scope, it will automatically `delete` the `test` object you created. The caller can however pass it elsewhere if it wants some other function to have the object.

Problem

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.

Original source