Reputation: 1
In the code below, drvdCls
derives from bseCls
. This code compiles and runs as it is. I however find an issue here: newBse
will get deallocated after Test()
exits. Am I right?
bseCls* Test()
{
bseCls* newBse = new drvdCls();
drvdCls newDrvd;
newBse = &newDrvd;
return newBse;
}
Upvotes: 0
Views: 110
Reputation: 109089
No, it won't be automatically deallocated. Every call to new
must be matched by a call to delete
. But that's not the only problem with your code, you're also returning the address of a local variable from the function.
newBse = &newDrvd; // memory leak, pointer to previously allocated object is lost
return newBse; // newDrvd is destroyed when function exits, so returned
// pointer points to invalid memory
What you probably want to do is
bseCls* Test()
{
return new drvdCls();
}
Now the caller must call delete
on the returned pointer after using it. What you should do is
std::unique_ptr<bseCls> Test()
{
return new drvdCls();
}
Now the allocated object will automatically be delete
d when the returned unique_ptr
goes out of scope.
Upvotes: 1
Reputation: 168988
The object originally pointed to by newBse
will be leaked. When you assigned the address of newDrvd
to newBse
you are losing the pointer to the heap-allocated object, and you will not be able to delete
it. This memory will be unusable until the process terminates.
Additionally, you are returning the address of a stack-allocated object as a pointer, which is bad for two reasons:
bseCls
, but you will be using it as though it were.If you use the pointer returned by this function, you are invoking undefined behavior and your program has license to do anything.
Upvotes: 4