In question 1, you look at heap memory and stack memory. In short,
Mystruct S;
creates an S on the stack. When S goes beyond, it will be destroyed. Therefore, if S is inside the function, when the function returns, S is destroyed.
While
MyStruct *S = new MyStruct();
In a heap. This is a memory block reserved for variable storage programs, and S will store a pointer to the initial memory block of the new MyStruct. He will always be on the heap until you free him; if you do not free it when your program ends, you will receive an unfair memory leak.
To question 2 - the local MyStruct is destroyed when the function exits; a MyStruct pointer pointing to its return value points to an undefined scope. It can still work because the OS has not yet recovered memory, but this is definitely the wrong behavior - or a safe thing.
source share