Foo* foo1 = static_cast<Foo*>( alloca( sizeof( Foo ) * numTargets ) );
new (foo1) Foo(); // Statement 1: Calls constructor Foo()
Foo** foo2 = static_cast<Foo**>( alloca( sizeof( Foo* ) * numTargets ) );
new (foo2) Foo*(); // Statement 2: Doesn't calls constructor Foo()
In my current project, statements 1 & 2 are not present.
Not having statement#1 leads to crash (a bug) when an attempt is made to populate value in foo1[i]
. I fixed it by introducing statement#1. But I am not sure about few things :
- Should I use
new (foo1) Foo[numTargets ];
instead ofnew (foo1) Foo();
- Should I introduce statement#2 for safegaurding against any future bug? What impact does statement#2 have in actuality?
- How does the statement#1 help to prevent the crash?
- Is there any Memory leak in either of the cases? Do we have to call the destructor explicitly for both cases?