What are the reasons for avoiding macloc () and free () in C++?
What this article shares with you is about the reasons why you avoid using macloc () and free () in C++. The editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article. Without saying much, let's take a look at it with the editor.
Reason (reason)
Malloc () and free () do not support construction and destruction, and do not mix well with new and delete.
Malloc () and free () do not support construction and destructing, and do not integrate well with new/delete.
Example (sample)
Class Record {
Int id
String name
/ /...
}
Void use ()
{
/ / p1 may be nullptr
/ / * p1 is not initialized; in particular
/ / that string isn't a string, but a string-sized bag of bits
Record* p1 = static_cast (malloc (sizeof (Record)
Auto p2 = new Record
/ / unless an exception is thrown, * p2 is default initialized
Auto p3 = new (nothrow) Record
/ / p3 may be nullptr; if not, * p3 is default initialized
/ /...
Delete p1; / / error: cannot delete object allocated by malloc ()
Free (p2); / / error: cannot free () object allocated by new
}
In some implementations that delete and that free () might work, or maybe they will cause run-time errors.
In some implementation cases, delete and free () may be executable here, or may cause execution errors.
These are the reasons why C++ avoids using macloc () and free (). The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.