Consider a function that returns a Type*, and so it looks like it could allocate a Type in its definition, but you can’t tell for sure (there are many functions, and you don’t have the time to read their definitions).
How can you tell if you should delete the pointer returned or not? for example, this is the type:
struct MyStruct
{
MyStruct(void) { cout << "Created.\n"; }
~MyStruct(void) { cout << "Deleted.\n"; }
};
And this is the function:
MyStruct* Func1(void)
{
return (new MyStruct());
}
Func1 allocated a pointer, and you should later de-allocate it. but maybe the definition is something else, and the pointer shouldn’t be deleted.
My question is: How can you tell if to delete the pointer or not? for example: maybe the pointer is static?
MyStruct* Func2(void)
{
static MyStruct* ms = &MyStruct();
return ms;
}
De-allocating this pointer would crash the entire program.
Thanks in advance.
You can’t, and that is one reason why it’s a very bad idea to use raw pointers to manage memory. If an object needs deleting, then that should always be done automatically, using a smart pointer.
This also has the advantage that the dynamic object will always be deleted once you’ve finished with it, even if an exception gets thrown.
If you’re forced to use a badly-designed library with functions return pointers that might or might not need deleting, then your only choice is to either read the documentation or find a better library. It would be a good idea to immediately assign any pointer that needs deleting to a smart pointer, so you at least have exception safety.