问题
The expression new T[n]
may or may not initialize each object in the array, depending on what T
is.
How do I replicate this initialization behavior using an allocator
?
struct Foo
{
int x;
Foo() : x(1)
{ }
};
Foo *p = new Foo[1];
assert(p[0].x == 1);
回答1:
In C++03, the allocator interface only knows one way to initialize objects, and that's to copy from another object. C++11 has more.
You're asking for default initialization, which means (approximately), "either do nothing or call the default constructor". The allocator interface cannot do the latter in C++03.
I suppose you could write something like:
T *ra = allocator.allocate(1);
if (!is_pod<T>::value) {
// in C++03
allocator.construct(ra, T());
// in C++11
allocator.construct(ra);
}
That is_pod
test might be wrong, though. Check the standard for exactly what conditions default initialization does nothing. Obviously is_pod
doesn't exist in C++03, but I vaguely recall that Boost has something of the kind that works on most implementations.
I think that you're fighting the design here. The allocator interface was designed for use by containers. Containers were designed not to contain uninitialized elements, so they have no use for default initialization.
来源:https://stackoverflow.com/questions/11626299/how-to-exactly-simulate-new-tn-with-an-allocator