I'm going to state my understanding of what you're trying to do, which is not 100% clear to the respondents. Since you don't have a default constructor for your class, you cannot allocate them in an array using new[]. Your recourse is to invoke the constructors manually using placement new.
In general, try to make a default constructor for classes that need to be allocated with new[]. Then you can just go update them after you've allocated them. This is simpler and easier to read. For example, w = new K[number]; and delete[] w; handles everything for you, but it can only call the default constructor. So you must do "post construction initialization" with your own function to set them up the way you want.
If you really want to call the individual constructors using placement new, you can and it is safe. It's not my recommended design, but neither is it as evil as some might assume. Your code works, but you don't do anything with w after you're done, so it's a leak... but examining it in the debugger, it has called the constructor on each one, just like you wanted. You should note that you are reusing n in different scopes, which is confusing. You should disambiguate that. The n from allocate is being fed into each constructor.
One other important note though, and this is the disadvantage of the design of using placement new here. You must:
- Manually invoke the destructor on each element when you are done. Therefore, you must track the length of the array manually until freeing.
- Free
w the matching way it was allocated. Do not use delete[] if you didn't use new[].
reinterpret_castand calls tooperator new?