-2

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;
}
Davut Özcan
  • 109
  • 12
  • @FredOverflow Not the same, since that question doesn't discuss returning the address from the function. – Barmar Mar 12 '14 at 12:35

3 Answers3

2

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!

Marius Bancila
  • 15,287
  • 7
  • 44
  • 84
  • Really ? Does c++ calls destructor even if I use a pointer to it , if so then it is very dangerous to use such a function.Can you provide a link for reference if it is possible. – Davut Özcan Mar 12 '14 at 12:37
  • 1
    Constructors and destructs have nothing to do with pointers. A constructor is called when the object is created and the destructor is called when the object is destroyed. In case of objects that live on the heap, the constructor is called by `new` and the `destructor` by the `delete` operator. – Marius Bancila Mar 12 '14 at 12:43
  • Thank you for the reply , I think I got your point , but it seems to me not logical that c++ make an object destroyed while a pointer points to it. – Davut Özcan Mar 12 '14 at 12:56
  • 1
    @DavutÖzcan C++ has no standardized notion of Garbage Collection. – fredoverflow Mar 12 '14 at 13:19
2

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

Obj foo()
{
    Obj obj;
    return obj;
}
fredoverflow
  • 237,063
  • 85
  • 359
  • 638
0

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

Barmar
  • 596,455
  • 48
  • 393
  • 495