Placement new for contiguous memory
-
26-05-2021 - |
Question
I am facing some problems for using placement new for contiguous memory.Please guide me, if there is any other way to do this.
Please refer my code.
#include <new>
//================================================
class MyClass
{
private:
int ma;
public:
MyClass():ma(-1){}
};
//===========================================
int main()
{
// I am allocating the memory for holding 10 elements of MyClass on heap
void* pMyClass = ::operator new(sizeof(MyClass)*10);
//! Note :: the address of pMyClass1 and pMyClass will now point to same
//location after calling placement new
MyClass* pMyClass1 = :: new(pMyClass)MyClass();
//! Problem with this is that,
//! i can only instantiate the constructor for the base address. That is
//! pMyClass[0].
//! If i have to instantiate it for all the other instances,
//! that is pMyClass[1] to pMyClass[9], then how to do it ?
return 0;
}
Solution
You have the beginning of the memory in pMyClass, and the stride is sizeof(MyClass). So, what you need to do is for example:
MyClass* pMyClass2 = ::new((MyClass*)pMyClass + 1)MyClass();
OTHER TIPS
Try:
MyClass* pMyClass1 = :: new(pMyClass)MyClass[10];
You have to call the placement new inside a loop that iterates on the 10 contiguous chunks of memory:
int main()
{
void* pMyClass = ::operator new(sizeof(MyClass)*10);
MyClass* pMyClass1 = reinterpret_cast<MyClass*>(pMyClass);
for (size_t i=0; i<10; ++i) {
::new(pMyClass1++)MyClass();
}
// ...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow