The memory lifetime memory allocated by new keyword will remain valid until you call the delete here.
So this means that you may have memory with long lifetimes and the code may be passed around various
functions in your code.
So here, consider this.
Here let's make P one new integer 42.
Here an integer p to do something.
This is this is the function that we will create.
Here and delete P one and P one equals nullptr.
And here make the do something function here.
Integer Here.
Do something.
And here, return integer.
Here.
Or make.
Let's create a variable here.
Integer.
My Val and my Val.
This returned my Val here.
Here.
As you can see here, we cannot be.
We have to do typecast here.
And, uh, we got to do something here.
And as you can see here, we initialized p one to nullptr, but what about the P two here?
And this code creates a pointer and initializes the memory it points to and then passes the pointer
to a function which itself returns the pointer here.
So since the P one.
Since the p one pointer is no longer needed, it is deleted and assigned to nullptr so that it cannot
be used again.
So this code looks fine.
But the problem is what do you do with the pointer returned by the function?
Imagine here.
Let's change our function.
Now imagine this following function here.
P.
Here.
Uh, equals ten.
Because it's not p integer and return.
P integer.
So in in this code the calling do something.
Actually, we can if we do like this, we're going to get an error.
And that's why we have to call the cast and yeah, yeah, it's okay to use this here before the function.
So this calling do something creates a copy of a pointer, but not copy of what it points to.
So this means that when p one pointer is deleted here.
The memory it points to is no longer available.
And so the pointer p to here.
Points to the invalid memory.
So this problem can be addressed using a mechanism called resource acquisition initialization.
This means error i e here, which means using the features of C plus plus objects to manage resources.
So here I'm going to make it here, error here in C plus plus it needs classes and in particular copy
constructors and destructors.
So a smart pointer class can be used to manage a pointer so that when it copied, the memory it points
to is also copied here.
And the destructor is function that is called automatically when the object goes out of scope.
And so the smart pointer can use this free memory.
So don't worry, smart pointers and destructors will be covered in next lectures.