Dynamically allocating an array of objects

前端 未结 7 1686
挽巷
挽巷 2020-11-22 13:05

I have a class that contains a dynamically allocated array, say

class A
{
    int* myArray;
    A()
    {
        myArray = 0;
    }
    A(int size)
    {
           


        
7条回答
  •  無奈伤痛
    2020-11-22 13:15

    Using the placement feature of new operator, you can create the object in place and avoid copying:

    placement (3) :void* operator new (std::size_t size, void* ptr) noexcept;

    Simply returns ptr (no storage is allocated). Notice though that, if the function is called by a new-expression, the proper initialization will be performed (for class objects, this includes calling its default constructor).

    I suggest the following:

    A* arrayOfAs = new A[5]; //Allocate a block of memory for 5 objects
    for (int i = 0; i < 5; ++i)
    {
        //Do not allocate memory,
        //initialize an object in memory address provided by the pointer
        new (&arrayOfAs[i]) A(3);
    }
    

提交回复
热议问题