0

Is there any difference initialising a pointer with the keyword new or with a reference to an already-created object? In particular, is there a difference in terms of object lifetimes or memory leakage potential?

As an example, consider the following:

class Apple {
    // constructor, etc
};

Apple* doSomething() {
    Apple* ptr = new Apple();
    // do stuff
    return ptr;
}

Apple* doSomethingElse() {
    Apple a {/* constructor parameters */};
    Apple* ptr = &a;
    // do stuff
    return ptr;
}

int main() {
    Apple* ptr1 = doSomething();
    Apple* ptr2 = doSomethingElse();
    return 0;
}

At what point would the two Apple objects and the two (or rather four?) pointers go out of scope and/or be deleted?

Remellion
  • 166
  • 2
  • 7
  • @Remellion In the second function you are returning an invalid pointer because it points to a local object of the function that will not be alive after exiting the function. – Vlad from Moscow Jan 30 '20 at 10:34
  • For your doSomethingElse example please read [What is a dangling pointer?](https://stackoverflow.com/questions/17997228/what-is-a-dangling-pointer) – Brandin Jan 30 '20 at 14:13
  • The Apple you create is never deleted. In C++, when you create something with `new`, it is never deleted until you delete it yourself by writing `delete`. I recommend you look up the terms 'scope' and 'lifetime' and study the difference between these two. It sounds like you are conflating them somehow. – Brandin Jan 30 '20 at 14:15

0 Answers0