This is an example of my codes:
template <typename T> struct MyStruct {
T object;
}
template <typename T> class MyClass {
MyStruct<T>* structPool;
size_t structCount;
MyClass(size_t count) {
this->structCount = count;
this->structPool = new MyStruct<T>[count];
for( size_t i=0 ; i<count ; i++ ) {
//placement new to call constructor
new (&this->structPool[i].object) T();
}
}
~MyClass() {
for( size_t i=0 ; i<this->structCount ; i++ ) {
//explicit destructor call
this->structPool[i].object.~T();
}
delete[] this->structPool;
}
}
My question is, is this a safe way to do? Do I make some hidden mistake at some condition? Will it work for every type of object (POD and non-POD)?
No, because both your constructor and destructor are invoked twice. Because you have this:
When you construct a
MyStruct<T>the compile will construct the innerTand when you delete the object the innerTwill have the destructor called automatically.For this example, there is no need for placement new or an explicit destructor call.
Placement new would be useful if you allocate raw memory. For example, if you changed your new to:
then you would want to placement new and explict destructor call.