Uninitialized array of C ++ class instances

I searched, but could not find the answer to this question. Is there any way to tell the operator newnot to call class constructors?

MyObject* array = new MyObject[1000];

It will call a MyObject()thousand times! I want to fill out the allocated memory on my own and do not need any information initialized in the constructor. Usage malloc()is not very harmonious C ++ imho code.

MyObject* array = (MyObject*) malloc(sizeof(MyObject) * 1000);
+5
source share
4 answers

C ++ equivalent for mallocis a distribution function operator new. You can use it like this:

MyObject* array = static_cast<MyObject*>(::operator new(sizeof(MyObject) * 1000));

Then you can create a specific object with a new location:

new (array + 0) MyObject();

Replace 0with any offset you want to initialize.

, , . , std::map<int, MyObject> std::unordered_map<int, MyObject>, MyObject .

std::unordered_map<int, MyObject> m;
m[100]; // Default construct MyObject with key 100
+4

, malloc ++. malloc , . , , , ++. , , C ++.

, - MyObject, , ++.

+4

std::vector

std::vector<MyObject> v;

v.reserve(1000); // allocate raw memory
v.emplace_back(42); // construct in place

( ( ), std::vector ):

typedef std::aligned_storage<sizeof(MyObject), std::alignment_of<MyObject>::value>::type Storage;
MyObject* myObjects(reinterpret_cast<MyObject*>(new Storage[1000]));

new (myObjects + 42) MyObject(/* ? */); // placement new
(*(myObjects + 42)).~MyObject();
+3

Have you timed it? Will it take too long? Does this happen only once during the execution of your program, for example, at the beginning? First determine that this is really a problem.

Do you really need to highlight 1000 objects this way?

Also, if constructors are not called, how will objects be constructed?

0
source

All Articles