Example of C ++ placement new usage ZZ

Source: Internet
Author: User
Example of http://www.blogjava.net/dongwq/archive/2010/04/20/318874.html C ++ placement new usage zz2009-12-17

When processing memory allocation, C ++ programmers use the new operator (Operator new) To allocate memory, and use the delete operator (Operator Delete) To release the memory. This is an example of the new operator.

Class ctest
{
/* Member functions and member data */
};

//... Code

// Allocate an object
Ctest * Ptest = new test;
// Allocate an array with ten objects (ctest must have a default constuctor ))
Ctest * p10tests = new test [10];

Although this method works well most of the time, it is still used in some cases.NewIt is annoying, for example, when you want to reassign an array or construct an object on the pre-allocated memory.

For example, in the first case, the efficiency of allocating an array is very low:

// Allocate an array with 10 objects
Ctest * ptests = new test [10];
//...
// Suppose we need 11 objects now
Ctest * pnewtests = new test [11];
//... We must copy the original object to the newly allocated memory.
For (INT I = 0; I <10; I ++)
Pnewtests [I] = ptests [I];
Delete ptests;
Ptests = pnewtests;

If you want to create objects in the pre-allocated memory, the default new operator will not work. To solve this problem, you can usePlacement newStructure. It allows you to construct a new object to the pre-allocated memory:

// Buffer is a void pointer (void *)
// The parts enclosed in square brackets [] are optional.
[Cyourclass * pvalue =] New (buffer) cyourclass [(parameters)];

The following are some examples:

# Include <New>

Class ctest
{
Public:
Ctest ()
{}
Ctest (INT)
{}
/* Code */
};

Int main (INT argc, char * argv [])
{
// For the purpose of this example, we do not consider memory alignment.
Char strbuff [sizeof (ctest) * 10 + 100];
Ctest * pbuffer = (ctest *) strbuff;

// Default Structure
Ctest * pfirst = new (pbuffer) ctest;

// Default Structure
Ctest * Consumer cond = new (pbuffer + 1) ctest;

// Construct with parameters;
// Ignore the pointer returned
New (pbuffer + 2) ctest (5 );

// Construct with Parameters
Ctest * pfourth = new (pbuffer + 3) ctest (10 );

// Default Structure
Ctest * pfifth = new (pbuffer + 4) ctest ();

// Construct multiple elements (default)
Ctest * pmultipleelements = new (pbuffer + 5) ctest [5];
Return 0;
}

When you have your own memory buffer or you implement your own memory allocation policy,Placement newIt is useful. In fact, it is widely used in STL.Placement newTo allocate memory to the container. Each container class has a template parameter that describes the alcator used to construct/analyze the object ).

In usePlacement newRemember the following points:

  • Add the header file # include <New>
  • You can use placement new to construct elements in an array.
  • To parse an object allocated with placement new, you should manually call the Destructor (there is no "Placement Delete "). Its syntax is as follows:

Pfirst-> ~ Ctest ();
Cond-> ~ Ctest ();

In the previous incident, I asked a question about placement new. A senior man gave some truth and said:

: The objects on the stack (Note: it is a class object, and the char type is not required, which will be mentioned later) should be placed on the alignment address.

However, after a personal experiment, I found that this is not the case.

For example:
Int main ()
{
Char C1 = 'a ';
Char C2 = 'B ';
Char C3 = 'C ';
Char C4 = 'D ';
Char C5 = 'E ';

// -------- Verify whether the four addresses are multiples of 4 --------------//
If (INT) (& C1) % 4 = 0)
Cout <"C1: yes" <Endl;

If (INT) (& C2) % 4 = 0)
Cout <"C2: yes" <Endl;

If (INT) (& C3) % 4 = 0)
Cout <"C3: yes" <Endl;

If (INT) (& C4) % 4 = 0)
Cout <"C4: yes" <Endl;

If (INT) (& C5) % 4 = 0)
Cout <"C5: yes" <Endl;

Cout <(INT) (& C1) <Endl // address of the output four characters (the output result is a multiple of 4)
<(INT) (& C2) <Endl
<(INT) (& C3) <Endl
<(INT) (& C4) <Endl
<(INT) (& C5) <Endl;
}
-----------------------------
The above execution results are multiples of 4 in VC.
--------------

--> Question 1: If the address of the space allocated on the stack is a multiple of 4, it means that the space allocated by the system is a multiple of 4, right ???

--> Question 2: what happens if the address of an object is not a multiple of 4 ?? Can you give me a brief description?

--> Question 3: What is the universality of address alignment ???
-------------
Procedure 1:
Class C1
{
Int I;
Char C;
};
Cout <sizeof (C1) <Endl; // output result: 8 (a multiple of 4)
Procedure 2:
Class C2
{
Char C1;
Char C2;
};
Cout <sizeof (C2) <Endl; // output result: 2 (the char type in the previous one is also given 4 bytes. How can this place be given a byte ??)
--> Question 4: The following program is derived from Program 2 above.
Class C2 // sizeof (C2) = 2. The result in the VC experiment is not 4.
{
Char C1;
Char C2;
};
// ---------- Use the placement new method to create an object ----------------
Void * PTR = Operator new (100); // allocate memory
C2 * pointer = (C2 *) PTR; // type conversion
String * str1 = new (pointer) C2 (); // create a C2 object
String * str2 = new (pointer + 1) C2 (); // create another object
String * str3 = new (pointer + 2) C2 (); // create another object

Cout <(INT) (str1) <Endl // result: 3608720 (a multiple of 4)
<(INT) (str2) <Endl // result: 3608722 (not a multiple of 4 )!!
<(INT) (str3) <Endl; // result: 3608724 (not a multiple of 4 )!!

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.