C++ dynamic allocation of class array -
assume class x
constructor function x(int a, int b)
i create pointer x x *ptr;
allocate memory dynamically class.
now create array of object of class x
ptr = new x[sizeofarray];
until fine. want creation of above array of objects should invoke constructor function x(int a, int b)
. tried follows:
ptr = new x(1,2)[sizeofarray];
as expected gave me compile time error
error: expected ';' before '[' token|
how can create array of objects invoke constructor?
sizeofarray
entered user @ runtime.
edit: wanted achieve in not possible answered zenith or complex . how can use std::vector
same?
this seems job placement new...
here's basic example:
#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 new objects going placed char* memory = new char[element_count * element_size]; // next insertion index size_t insertion_index = 0; // construct new x in address (place + insertion_index) void* place = memory + insertion_index; x* x = new(place) x(1, 2); // advance insertion index insertion_index += element_size; // check out new object cout << "x(" << x->a << ", " << x->b << ")" << endl; // explicit object destruction x->~x(); // free memory delete[] memory; }
edit: if i've understood edit, want this:
#include <vector> // init vector of `element_count x x(1, 2)` std::vector<x> vec(element_count, x(1, 2)); // can still raw pointer array such x* ptr1 = &vec[0]; x* ptr2 = vec.data(); // c++11
Comments
Post a Comment