[C + + primer] Optimizing memory allocation

Source: Internet
Author: User

memory allocation for C + + is a typed operation: New allocates memory for a particular type and constructs an object of that type in the newly allocated memory. The new expression automatically runs the appropriate constructor to initialize each dynamically allocated class type Object.

The fact that new allocates memory on a per-object basis might impose unacceptable runtime overhead on some classes, such that a class might need to be allocated faster with user-level class-type object allocations. The common strategy used by such classes is to pre-allocate memory for creating new objects, and to construct each new object in pre-allocated memory when needed. Other classes want to allocate the required memory to their own data members by a minimum size.

In each case (pre-allocating memory to hold a user-level object or saving internal data for a class) requires that the memory allocation be separated from the object construction. The obvious reason for separating memory allocations from object constructs is that it is wasteful to construct objects in pre-allocated memory and may create objects that are never used. When a pre-allocated object is actually used, the object being used must be re-assigned to the new value. More subtly, if pre-allocated memory must be constructed, some classes will not be able to use it. For example, consider a vector, which uses a pre-allocation strategy. If you must construct a pre-allocated in-memory object, you cannot have a base type of vector--vector that does not have a default constructor, and there is no way to know how to construct those objects.

1. Memory allocation in C + +

In C + +, memory allocation and object construction are closely intertwined, just as objects and memory collections are. When using the new expression, allocate memory and construct an object in that memory, and when using the delete expression, call the destructor to undo the object and return the memory used by the object to the system.

When you take over memory allocations, you must handle both tasks. When allocating raw memory, you must construct the object in that memory, and you must ensure that the objects are properly revoked before releasing the memory.

Note: An object that is not constructed in memory is assigned instead of initialized, and its behavior is undefined. For many classes, doing so causes the runtime to crash. Assignment involves deleting an existing object, and if there is no existing object, the action in the assignment operator will have a disastrous effect.

C + + provides the following two ways to allocate and release raw memory that is not constructed:

1) The allocator class, which provides a perceptual type of memory allocation. This class supports an abstract interface to allocate memory and then use that memory to save objects.

2) Operatornew and Operatordelete in the standard library, which allocate and release raw, untyped memory that requires size.

C + + also provides different ways to construct and revoke objects in raw memory.

1) The allocator class defines the members named construct and destroy as their names indicate: The construct member initializes the object in the non-constructed memory, and the destroy member runs the appropriate destructor on the object.

2) position the new expression to accept a pointer to the non-constructed memory and initialize an object or an array in that space.

3) You can directly invoke the object's destructor to undo the object. Running a destructor does not release the memory in which the object resides.

4) Algorithms Uninitialized_fill and uninitialized_copy execute like fill and copy algorithms, except that they construct objects at the destination rather than assigning values to objects.

2, Allocator class

The allocator class is a template that provides typed memory allocations as well as object construction and revocation.

The allocator class separates memory allocations from object constructs. When the allocator object allocates memory, it allocates the appropriate size and arranges the space to hold the object of the given type. However, the memory it allocates is not constructed, and the allocator user must construct and destroy the objects placed in that memory respectively.

3. operator new function and operator delete function

Using the new expression: string* sp =new string ("initialized");

3 steps actually occur:

1) Call the standard library function named operator new. Allocates large enough raw, untyped memory to hold an object of the specified type.

2) Run a constructor of the type that constructs the object with the specified initializer.

3) Returns a pointer to the new assignment and constructs the object.

(Summary: Allocating memory, constructing objects, returning object pointers)

Use the delete operator to delete an SP; When you delete an object, two steps occur:

1) Run the appropriate destructor on the pointed object.

2) call the standard library function named operator delete to release the memory of the object.

(Summary: destructors, freeing space)

Note : The new expression differs from the operator new function (which is different):
1) The behavior of the new and delete expressions cannot be redefined;
2) The new expression is obtained by invoking the memory of the operator new function, and then constructing an object in that memory, undoing an object by executing a delete expression, and then invoking the operator delete function to free the memory used by the object.

operator new AND operator delete have two different versions. Each version supports the associated new and delete expressions.

void *operator New (size_t); Allocate an object;

Vodi *operator New [] (size_t); Allocate an array;

void operator Delete (void*); Free an object;

void operator delete[] (void*); Free an array;

Although operator new and operator delete are designed for use with new and delete expressions, we can still use them to obtain the non-constructed memory. This is somewhat similar to allocator's allocate and DEALLOCATE members.

In general, using allocator is more type-safe than using the operator new and operator delete functions directly.

4. Positioning the new expression (placement new)

The standard library functions operator new AND operator delete are low-level versions of the allocate and deallocate members of allocator, and they all allocate but do not initialize memory.

The position new expression Initializes an object in the allocated raw memory, unlike the other versions of new , where it does not allocate memory. Instead, it takes a pointer to the allocated but not constructed memory and initializes an object in that memory. In fact, locating the new expression allows us to construct an object at a specific, pre-allocated memory address.

Position the new expression form:

New (place-address) type; Constructs type object at pointer p;

New (place-address) type (initializer list); Constructs an object with an initialization list at pointer p;

Where place_address must be a pointer, and Initializer-list provides a (possibly empty) initialization list to use when constructing the newly allocated object.

using a positional new expression is more flexible than using the construct member of the allocator class. position new When initializing an object, it can use any constructor and directly build the object, while the construct function always uses the copy constructor.

5. Display the call of a destructor

We can use the explicit invocation of a destructor as a low-level choice to invoke the destroy function. The effect of an explicit call to a destructor is to properly clear the object itself. However, it does not release the memory that the object occupies, and if necessary, the memory space can be reused.

For programs that use the anchor new expression to construct an object, the call destructor is displayed:

for (t* p=first_free;p!=elements;/*empty*/)    p->~t ();      Call the destructor;

[C + + primer] Optimizing memory allocation

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.