Three usage methods of new

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.