When C++ uses new
The data developed by the heap area is manually opened by the programmer and released manually, and the operator delete is released.
grammar:new data type
The data created with new will return a pointer of the type corresponding to the data.
When creating a class, memory space will be opened and the constructor will be called.
So the following code can appear
Building * building;(Declare creation building)
building = new Building; (new creates an unnamed object)
Added on 2022.12.25.
also,usebuilding = new Building; When generating a class, similar to calling a parameterless construct, but there is stillthe difference。
building = new Building , approximately regarded as building = new Building();
Reposted in the link
Many people say that adding brackets calls constructors without parameters, and calling default constructors or unique constructors without brackets. This is problematic.
For custom class types:
If the class does not define a constructor (the default constructor is synthesized by the compiler) and does not have a virtual function, then class c = new class; will not call the synthetic default constructor, while class c = new class(); will call the default constructor.
If the class is not definedConstructor(The default constructor is synthesized by the compiler) But there are virtual functions, then class c = new class; and class c = new class(); will call the default constructor.
If the class defines the default constructor, then class c = new class; and class c = new class(); will call the default constructor.
For built-in types:
int *a = new int; will not initialize the applied int space, while int *a = new int(); will initialize the applied int space to 0.
The difference between the following two statements is: the value in the first dynamic application space is a random value, and the second is initialized, with the value in it being 0:
- int *p1 = new int[10];
- int *p2 = new int[10]();
Conclusion: Don't use new without brackets.