本篇文章給大家分享的是有關C++中避免使用macloc()和free()的原因是什么,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。
malloc() and free() do not support construction and destruction, and do not mix well with new and delete.
malloc()和free()不支持構造和析構,和new/delete融合得也不好。
Example(示例)
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<Record*>(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.
在某些實現的的情況下,這里delete和free()可能可以執行,也可能引起執行時錯誤。
以上就是C++中避免使用macloc()和free()的原因是什么,小編相信有部分知識點可能是我們日常工作會見到或用到的。希望你能通過這篇文章學到更多知識。更多詳情敬請關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。