I have some questions concerning the difference between the keyword new and & in a certain context.
Let’s say this is my code:
struct Base {};
struct Foo : Base {};
struct Storage
{
void save(Base * object) {}
Base * content;
};
int main()
{
Storage s1, s2;
s1.save(new Foo());
s2.save(&Foo());
}
After the execution of main, s1 will hold a pointer to an object of type Foo. Yet s2 will hold a pointer to an object of type Base. s2.content will only point towards an object of type Foo until the save method has finished execution.
Please correct me if I am wrong:
As far as I understand new Foo() creates a pointer to a new object of type Foo. &Foo() on the other hand first creates a new object of type Foo and then points to it.
What exactly is the difference between new Foo() and &Foo() then? Obviously both give you a pointer to an existing object of type Foo.
Why does the object created by new Foo() persist after execution of the save method whereas the object created via &Foo() does not?
May it be that &Foo() creates a temporary object, which will cease to exist after the execution of save? If yes, how can I prolong the life of the object created via &Foo() to make it live (at least) until the destruction of s2?
Edit 1:
Thank you very much for the quick answers! I'm simply using Visual Studio, so maybe &Foo() compiling is some Microsoft specific stuff...