How to exactly simulate new T[n] with an allocator?

醉酒当歌 提交于 2019-12-23 01:16:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!