Is this the proper way of freeing Pointer Memory in c++
this is a example, I am struck with whether it is a a proper way of freeing the pointer assigned memory
char* functionTest()
{
char *a = new char[10];
return a;
}
int main()
{
char *b;
b=functionTest();
delete[] b;
return 0;
}
This is a very beginner question but still would like to clear my doubt. edited from delete to delete[] thanks @sharptooth. thanks in advance.开发者_如何学运维
Technically correct C++ (as of this time with the edit using delete[]
)
The code would compile and run without errors.
However in production C++ code you will very rarely use new[] and delete[], and will be far more likely to use vector, or for string handling use string.
If you do really want to allocate an array with new[] you may well wish to use boost::shared_array to manage its deletion. Failing that you could use shared_ptr but would have to put in your own deleter that calls delete[].
This technique is called RAII (Resource Acquisition Is Initialisation), which ensures that for any resource you allocate, you are already taking care of its subsequent disposal regardless of what happens subsequently (including any exceptions that may be thrown).
Here's a nice technical description of the differences between delete
and delete[]
:
http://blogs.msdn.com/b/oldnewthing/archive/2004/02/03/66660.aspx
精彩评论