C++ Is there a difference between creating obj with new keyword and creating directly [duplicate]

StackOverflow https://stackoverflow.com/questions/22351631

Вопрос

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;
}
Это было полезно?

Решение

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!

Другие советы

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top