Is there any difference between fncs: operator new and operator new[] (NOT new and new[] operators)? Except of course call syntax? I\'m asking because I can allocate X numbe
In your example code, you're using placement new to perform the construction that operator new[] performs automatically - with the difference that new[] will only perform default construction and you're performing a non-default placement construction.
The following is more or less equivalent to your example:
#include
using namespace std;
struct X
{
int data_;
X(int v=0):data_(v){}
};
int main(int argc, char* argv[])
{
unsigned no = 10;
X* xp = new X[no];
for (unsigned i = 0; i < no; ++i) {
X tmp(i);
xp[i] = tmp;
}
for (unsigned i = 0; i < no; ++i)
{
cout << (xp[i]).data_ << '\n';
}
delete[] xp;
return 0;
}
The differences in this example are:
new is a pretty advanced technique that isn't often used, so isn't often understood)I think that in general, using new[]/delete[] is a much better than allocating raw memory and using placement new to construct the objects. It pushes the complexity of the bookkeeping into those operators instead of having it in your code. However, if the cost of the "default construct/set desired value" pair of operations is found to be too costly, then the complexity of doing it manually might be worthwhile. That should be a pretty rare situation.
Of course, any discussion of new[]/delete[] needs to mention that using new[]/'delete[]should probably be avoided in favor of usingstd::vector`.