Why is the dynamic distribution of C ++ new and delete?
Because the malloc function and the corresponding free function cannot call constructor and destructor, this destroys the space allocation and initialization functions. So new and delete are introduced.
// ================================================ ==============================================
// Name: main. cpp
// Author: ShiGuang
// Version: www.2cto.com
// Copyright: sg131971@qq.com
// Description: Hello World in C ++, Ansi-style
// ================================================ ==============================================
# Include <iostream>
# Include <string>
Using namespace std;
Class aa
{
Public:
Aa (int a = 1)
{
Cout <"aa is constructed." <endl;
Id =;
}
Int id;
~ Aa ()
{
Cout <"aa is completed." <endl;
}
};
Int main (int argc, char ** argv)
{
Aa * p = new aa (9 );
Cout <p-> id <endl;
Delete p;
Cout <"" <endl;
Aa * q = (aa *) malloc (sizeof (aa ));
Cout <q-> id <endl; // random number indicates that the constructor has not been called.
Free (q); // destructor not called
}
Running result:
Aa is constructed.
9
Aa is completed.
3018824
The heap space is not dynamically released along with the function, so programmers must manage it independently.
// ================================================ ==============================================
// Name: main. cpp
// Author: ShiGuang
// Version:
// Copyright: sg131971@qq.com
// Description: Hello World in C ++, Ansi-style
// ================================================ ==============================================
# Include <iostream>
# Include <string>
Using namespace std;
Class aa
{
Public:
Aa (int a = 1)
{
Cout <"aa is constructed." <endl;
Id =;
}
~ Aa ()
{
Cout <"aa is completed." <endl;
}
Int id;
};
Aa & m ()
{
Aa * p = new aa (9 );
Delete p;
Return (* p );
}
Int main (int argc, char ** argv)
{
Aa & s = m ();
Cout <s. id; // The result is a random number, indicating that it is released.
}
Running result:
Aa is constructed.
Aa is completed.
4984904
The internal application space of the function must be released in time. Otherwise, repeated memory application and lost memory may occur.
// ================================================ ==============================================
// Name: main. cpp
// Author: ShiGuang
// Version:
// Copyright: sg131971@qq.com
// Description: Hello World in C ++, Ansi-style
// ================================================ ==============================================
# Include <iostream>
# Include <string>
Using namespace std;
Class aa
{
Public:
Aa (int a = 1)
{
Cout <"aa is constructed." <endl;
Id =;
}
~ Aa ()
{
Cout <"aa is completed." <endl;
}
Int id;
};
Void p ()
{
Aa * s = new aa [9999];
}
Int main (int argc, char ** argv)
{
For (;;)
P ();
Return 0;
}
From Study Notes of sg131971