Constructs an object in a predefined memory location

Source: Internet
Author: User

People often ask a C + + question: How do you construct an object in a predefined memory location? There are many useful applications for constructing an object in a predefined memory buffer. For example, a custom garbage collector can use a large preconfigured memory buffer, in which the user constructs its object. When these objects are no longer needed, their storage space is automatically retracted.

This technique is also useful in time-focused applications. Constructing an object in a pre-configured memory buffer is a "time constant" operation, because the program allocation operation itself does not waste valuable time. Also note that dynamic memory allocation may fail when the system does not have enough memory. Therefore, it is sometimes unavoidable to allocate a large enough buffer for the application of the task.

Many applications need to construct different types of objects at a given time. Think of an example where a GUI application can create a memory buffer and repeatedly construct and destroy different types of objects in the buffer, depending on the user's input, each time, displaying a different dialog box, using duplicate allocations and freeing memory.

C + + provides several features to facilitate the task of constructing an object in a predetermined memory location. Among these features is a special form of the new operator called "Locate new" (placement new) operation, and an explicit destructor. The implementation method is as follows:

First step: Allocate a sufficient memory buffer to hold the object of the given type. If you want to construct different types of objects at a time, you need to allocate at least one buffer to the size of the largest object's space. A preconfigured buffer is an array of pure characters that are allocated in the available memory space.

char * buff = new char [sizeof (Foo) ];

Once a buffer is allocated, each type of object can be constructed in the buffer. To do this, use the special version of the new operator ("locate new") to buffer the address to the placement new parameter. In order to use placement new, you must include the standard header file <new>. In the following code fragment, the placement new operation is used to construct an object of type Foo on the memory address buff.

#include <new>
Foo * pfoo = new (buff) Foo; //使用new操作在buff上构造一个 Foo

Placement new takes the previously allocated buffer (buff) address as a parameter and constructs the object of the given type on this buffer. He returns a pointer to the constructed object, which uses the same pointer as usual.

unsigned int length = pfoo->size();
pfoo->resize(100, 200);
length = pfoo->size();

When you no longer need this object, you must explicitly call its destructor free space. There are some tricks to doing this because many people mistakenly assume that the object will be destroyed automatically. The program will have unpredictable consequences if you forget to explicitly call the destructor before you construct another object in the preconfigured buffer or before you release the buffer. An explicit destructor declaration is as follows:

pfoo->~Foo(); //显式调用析构函数

In other words, an explicit destructor is the same as a normal member function call, except that the name differs slightly from the ordinary member function. Once the object is destroyed, another object can be constructed again in the preconfigured memory. In fact, this process can be repeated indefinitely: Construct an object, destroy it, and then reuse the preconfigured buffers to construct the new object.

A predefined buffer must be freed when a predefined buffer is no longer needed, or when the application shuts down. Use delete[] To complete this task, because the predefined buffer is an array of characters. The following code contains a complete example of all the steps, including the final buffer release:

#include <new>
 void placement_demo()
 {
  //1. 预分配缓冲
  char * buff = new char [sizeof (Foo) ];
  //2. 使用 placement new
  Foo * pfoo = new (buff) Foo;

  //使用对象
  unsigned int length = pfoo->size();
  pfoo->resize(100, 200);
  //3. 显式调用析构函数
  pfoo->~Foo();

  //4. 释放预定义的缓冲
  delete [] buff;
 }

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.