Question about the delete operator of C++.

Asked 2 years ago, Updated 2 years ago, 21 views

In C++, new uses if(!p) to check memory allocation, but is there a way to check if delete returned memory? And when I use new to allocate memory, should delete be used in the main, should I use it in the destructor, or where?

c++

2022-09-21 10:54

1 Answers

In C++, new uses if(!p) to check memory allocation, but is there a way to check if delete returned memory?

new throws either the std::bad_alloc exception or the constructor throws an exception if memory allocation fails. Unless an exception occurs, verification through if is meaningless because the address substituted in the pointer is always the allocated memory address.

For delete, make sure to release the memory address you entered. If an exception is thrown at the destructor, the destructor routine may not run completely, causing problems with resource release, but at least the memory entered in delete will be released. Therefore, there is no need to check, and there is no possible method within the C++ language range.

If new did not make an exception and the memory was not created, or delete did not release the memory, it is a bug in the C++ language implementation or a bug in the system. This is a problem outside the realm of C++.

And when I use new to allocate memory, should delete be used in the main, should I use it in the destructor, or where?

It is correct to delete it from the location where you have ownership. It must be released from main() just because it was created with newThere is no rule that it should be released from the annihilation.

Incorrect ownership management of memory caused a memory leak, so starting with C++ 11, we introduced smart pointers such as std::unique_ptr and std:shared_ptr. owner< T* > .


2022-09-21 10:54

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.