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?