It\'s an exercise from C++ Primer 5th Edition:
Exercise 16.26: Assuming NoDefault is a class that does not have a default constructor, can we e
As already said, the default constructor is required to create vector of objects. However, if one were to create a classic dynamic array (contiguous area of memory), it would be possible to address the lack of a default constructor using the placement new syntax:
#include
struct Foo {
explicit Foo(int a): a(a) {}
int a;
};
int main() {
void* mem = operator new[](10*sizeof(Foo));
Foo* ptr = static_cast(mem);
for (int i = 0; i < 10; ++i ) {
new(&ptr[i])Foo(i);
std::cout << ptr[i].a;
}
return 0;
}