简体   繁体   中英

C++ use operator delete for auto (stack) pointer

Must I use operator delete for stack pointer?

For example:

User * p = new User;
delete p;              //needed?

When you use delete you are not deleting the pointer, so it makes no difference whether it is a stack pointer or any other kind of pointer.

When you use delete you are deleting the block of memory pointed by the pointer. If that block was allocated with new , then it's always on the heap. (If it was not allocated with new , then you should not delete it.)

The other angle is that no, you must not use operator delete , because you should never use naked pointers in non-library code.

In modern C++, your example should be:

std::unique_ptr<User> p = std::make_unique<User>();

No delete and no new in sight.

Note : in this particulate case, make_unique could be substituted for new painlessly, but since in other examples it might not be, it's a good practice to teach yourself - make_unique is a function to use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM