Dynamic distribution of C ++ class arrays

Assume that a class Xwith a constructor functionX(int a, int b)

I am creating a pointer to X as a X *ptr;dynamic allocation of memory for the class.

Now to create an array of class X object

 ptr = new X[sizeOfArray];

everything is still fine. But what I want to do is create the above array of objects that should call the constructor function X(int a, int b). I tried the following:

ptr = new X(1,2)[sizeOfArray]; 

As expected, it gave me a compile-time error

error: expected ';' before '[' token |

How to create an array of objects to call the constructor?

SizeOfArray entered by the user at runtime.

EDIT: , , , , . , std::vector ?

+4
3

...

:

!

#include <iostream>
#include <cstddef>  // size_t
#include <new>      // placement new

using std::cout;
using std::endl;

struct X
{
    X(int a_, int b_) : a{a_}, b{b_} {}
    int a;
    int b;
};

int main()
{
    const size_t element_size   = sizeof(X);
    const size_t element_count  = 10;

    // memory where new objects are going to be placed
    char* memory = new char[element_count * element_size];

    // next insertion index
    size_t insertion_index = 0;

    // construct a new X in the address (place + insertion_index)
    void* place = memory + insertion_index;
    X* x = new(place) X(1, 2);
    // advance the insertion index
    insertion_index += element_size;

    // check out the new object
    cout << "x(" << x->a << ", " << x->b << ")" << endl;

    // explicit object destruction
    x->~X();

    // free the memory
    delete[] memory;
}

EDIT. , - :

!

#include <vector>
// init a vector of `element_count x X(1, 2)`
std::vector<X> vec(element_count, X(1, 2));

// you can still get a raw pointer to the array as such
X* ptr1 = &vec[0];
X* ptr2 = vec.data();  // C++11
+5

++, :

  • vector.

:

+4

You do not say if it sizeOfArrayis a variable or a constant. If this is a (small) constant, you can do it in C ++ 11:

X* ptr = new X[3] { {1,2}, {1,2}, {1,2} };
0
source

Source: https://habr.com/ru/post/1612776/


All Articles