Question

I have function returns a pointer like ;

Obj * foo()
{
    Obj obj;
    return &obj;
}

Is there a difference between previous function and the next one

Obj * foo2()
{
    Obj *ptr = new Object();
    return ptr;
}
Was it helpful?

Solution

Yes, it is. The first one creates an object on the stack and return its address. When the function returns the stack unwinds and the object gets destroyed. Therefore the caller ends up with a dangling pointer.

The second allocates an object on the heap and returns the address. The object is valid and will continue to be so until the caller explicitly deletes it.

You should never do the first approach!

OTHER TIPS

In the first version, you are returning a dangling pointer. You should return by value instead:

Obj foo()
{
    Obj obj;
    return obj;
}

The first function is incorrect. You're returning a pointer to a local object, but all local objects are destroyed when the funcition returns.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top