문제

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