本文介绍了如何使用分配器精确地模拟新的T [n]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

表达式 new T [n] 可能会也可能不会初始化数组中的每个对象,取决于如何使用 allocator 复制此初始化行为?

$ <$ p $ b

  struct Foo 
{
int x;
Foo():x(1)
{}
};

Foo * p = new Foo [1];
assert(p [0] .x == 1); $ c $ b
在C ++ 03中,分配器接口只知道一种方式来初始化对象,并且这是从另一个对象复制。 C ++ 11有更多。



你要求的默认初始化,这意味着(大约),无关或调用默认构造函数。分配器接口不能在C ++ 03中做后者。



我想你可以这样写:

  T * ra = allocator.allocate(1); 
if(!is_pod< T> :: value){
// in C ++ 03
allocator.construct(ra,T());
// in C ++ 11
allocator.construct(ra);
}

is_pod 可能是错的,虽然。检查标准是什么条件默认初始化什么也不做。显然,在C ++ 03中不存在 is_pod ,但是我仍然模糊地回忆起Boost具有可以在大多数实现中使用的类型。



我认为你在这里打击设计。分配器接口是为容器使用而设计的。容器设计为不包含未初始化的元素,因此它们没有用于默认初始化。


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);
解决方案

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.

这篇关于如何使用分配器精确地模拟新的T [n]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 13:46