Home > Article > Backend Development > When using new in the constructor in C++, you need to pay attention to these things!
Recommended study: "c Tutorial"
C Precautions for using new in the constructor
If you use new in the constructor to initialize a pointer member, you should use delete
new and delete must be compatible with each other. new corresponds to delete, new[] corresponds to delete[]
If there are multiple constructors, new must be used in the same way, either with brackets or neither. bring. Since there is only one destructor, all constructors must be compatible with it.
The exception to the above is that you can use new to initialize the pointer in one constructor, and initialize the pointer to null in another constructor. This is because delete (either with brackets or without brackets) can be used for null pointers.
C has traditionally preferred a simple 0 to the equivalent NULL, but C 11's nullptr is a better choice.
The above is the detailed content of When using new in the constructor in C++, you need to pay attention to these things!. For more information, please follow other related articles on the PHP Chinese website!