In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article is about how to use new and delete in C++. Xiaobian thinks it is quite practical, so share it with everyone for reference. Let's follow Xiaobian and have a look.
new and delete are called operators
Let's turn to disassembly and see
These two operators are essentially overloaded calls to the corresponding operators
What is the difference between malloc and new?
1.malloc opens memory by byte;new opens memory by specifying type new int[10]
So malloc opens up memory and returns void*
new is equivalent to the overloaded function operator new -> returns automatically to the specified class pointer int*
2.malloc is only responsible for opening up space, new not only has the function of malloc, but can initialize data.
new int(20);//initialize 20 new int[20]();//open array does not support initialization values, but supports writing empty parentheses, indicating that each element is initialized to 0, equivalent to calling int () to 0 for each element
3.malloc fails to open memory and returns nullptr pointer;new throws an exception of type bad_alloc
(That is, the new operator fails to open up memory. To expand its code into try catch, it cannot be compared with a null pointer by returning a value.)
try//The code for possible errors is placed in try { int *p = new int; delete []p; int *q = new int[10]; delete q; } catch (const bad_alloc &err)//catch exceptions of the corresponding type { cerr Call to operator delete overloaded function
Define the overloaded functions of new and delete in the global place, so that only the places involving new and delete in our entire project will call the overloaded functions of new and delete that we rewrite globally.
//first call operator new to open up memory space, and then call the object constructor (initialization) void* operator new(size_t size){ void *p = malloc(size); if (p == nullptr) throw bad_alloc(); cout
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.