For example,
class Test{
private:
int* foo;
public:
Test(int* foo){this->foo = foo;}
}
In this case, is there any way I can delete foo in the destructor? Will I have to delete foo in the destructor or at least set it to nullptr?
CodePudding user response:
Sure, you can. It is legal syntax. And depending on the rest of your program, it might do what you want, or it might be a double delete (delete the same pointer twice) which corrupts the heap and will lead to an eventual crash. (Debugging compilers might catch this.)
One of the reasons the C standard template library gave us shared_ptr
and unique_ptr
is that memory management by hand is hard. It isn't impossible; people did it (or tried to) for many, many years. But it was also a source of many runtime disasters, either the double delete (also called a premature free from the old malloc/free routines), or the opposite, a memory leak. Automatic memory management was one of Java’s selling points as a C/C -similar language without the memory bug risk. Later C# made the same pitch to users.
I suggest using the STL and thinking about the ownership semantics of your foo. Maybe the Test class should own it; maybe it should share it; maybe it should really have a weak reference. Can't tell from a program fragment. I can only say you should review modern ideas of memory management in C and adopt them.
CodePudding user response:
It is semantically legal to delete this pointer but I guess this isn't why you're asking. You're asking if this is a good idea.
Handling raw pointers in C is generally a bad practice and this problem is one example of why.
To make using of the class obvious for anyone who reads it, I would use std::unique_ptr
if you intend to take ownership of the pointer and either a reference or std::shared_ptr
if you don't.
Smart pointer objects will track for you if the pointer was already deleted and they will delete the pointer automatically in their destructors.
If you absolutely have to have a raw pointer and you need to check if it was deleted, I'm afraid your only option is to be consistent in assigning nullptr
to it right after deletion.