New can be used in three ways: new operator, operator new, and placement new.
New operator
New operator is the most common usage, such as Emp * e1 = new Emp; (Emp is a class) Here, new has two functions: space allocation and object initialization (constructor called)
Operator new
Operator new allocates only space without calling constructor, for example, Emp * e2 = (Emp *) operator new (sizeof (Emp ));
Placement new
Placement new initializes objects in the allocated space without allocating space. It calls the copy constructor, such as new (void *) e2) Emp (* tb1 );
The sample code is as follows:
// Emp. h
# Ifndef _ EMP_H _
# Define _ EMP_H _
Class Emp
{
Public:
Emp ();
Emp (const Emp & other );
~ Emp ();
};
# Endif/_ EMP_H _
// Emp. cpp
# Include "Emp. h"
# Include <iostream>
Using namespace std;
Emp: Emp ()
{
Cout <"Emp ..." <Endl;
}
Emp: Emp (const Emp & other)
{
Cout <"Copy Emp ..." <Endl;
}
Emp ::~ Emp ()
{
Cout <"~ Emp ..." <Endl;
}
// Main. cpp
# Include "Emp. h"
# Include <iostream>
Void main ()
{
Using namespace std;
// New operator allocates space and calls Constructor
Emp * e1 = new Emp;
// Operator new only allocates Space
Emp * e2 = (Emp *) operator new (sizeof (Emp ));
// Placement new does not allocate space. Call the copy constructor.
New (void *) e2) Emp (* e1 );
// Display and call the destructor
E2-> ~ Emp ();
// Only release space without calling the destructor
Operator delete (e2 );
// Call the destructor to release space
Delete e1;
}
Author: tbw