避免标准容器中元素的默认构造

时间:2011-08-28 01:54:39

标签: c++ stl initialization

我有兴趣构建一个uninitialized_vector容器,它在语义上与std::vector相同,但需要注意的是,否则将使用无参数构造函数创建的新元素将在没有初始化。我主要是想避免将POD初始化为0. 据我所知,通过将std::vector与一种特殊的分配器相结合,无法实现这一点。

我想以与std::stack相同的方式构建我的容器,它适应用户提供的容器(在我的例子中,std::vector)。换句话说,我想避免重新实现整个std::vector,而是围绕它提供一个“立面”。

是否有一种简单的方法可以从std::vector的“外部”控制默认构造?


这是我到达的解决方案,这启发了Kerrek的回答:

#include <iostream>
#include <vector>
#include <memory>
#include <algorithm>
#include <cassert>

// uninitialized_allocator adapts a given base allocator
// uninitialized_allocator's behavior is equivalent to the base
// except for its no-argument construct function, which is a no-op
template<typename T, typename BaseAllocator = std::allocator<T>>
  struct uninitialized_allocator
    : BaseAllocator::template rebind<T>::other
{
  typedef typename BaseAllocator::template rebind<T>::other super_t;

  template<typename U>
    struct rebind
  {
    typedef uninitialized_allocator<U, BaseAllocator> other;
  };

  // XXX for testing purposes
  typename super_t::pointer allocate(typename super_t::size_type n)
  {
    auto result = super_t::allocate(n);

    // fill result with 13 so we can check afterwards that
    // the result was not default-constructed
    std::fill(result, result + n, 13);
    return result;
  }

  // catch default-construction
  void construct(T *p)
  {
    // no-op
  }

  // forward everything else with at least one argument to the base
  template<typename Arg1, typename... Args>
    void construct(T* p, Arg1 &&arg1, Args&&... args)
  {
    super_t::construct(p, std::forward<Arg1>(arg1), std::forward<Args>(args)...);
  }
};

namespace std
{

// XXX specialize allocator_traits
//     this shouldn't be necessary, but clang++ 2.7 + libc++ has trouble
//     recognizing that uninitialized_allocator<T> has a well-formed
//     construct function
template<typename T>
  struct allocator_traits<uninitialized_allocator<T> >
    : std::allocator_traits<std::allocator<T>>
{
  typedef uninitialized_allocator<T> allocator_type;

  // for testing purposes, forward allocate through
  static typename allocator_type::pointer allocate(allocator_type &a, typename allocator_type::size_type n)
  {
    return a.allocate(n);
  }

  template<typename... Args>
    static void construct(allocator_type &a, T* ptr, Args&&... args)
  {
    a.construct(ptr, std::forward<Args>(args)...);
  };
};

}

// uninitialized_vector is implemented by adapting an allocator and
// inheriting from std::vector
// a template alias would be another possiblity

// XXX does not compile with clang++ 2.9
//template<typename T, typename BaseAllocator>
//using uninitialized_vector = std::vector<T, uninitialized_allocator<T,BaseAllocator>>;

template<typename T, typename BaseAllocator = std::allocator<T>>
  struct uninitialized_vector
    : std::vector<T, uninitialized_allocator<T,BaseAllocator>>
{};

int main()
{
  uninitialized_vector<int> vec;
  vec.resize(10);

  // everything should be 13
  assert(std::count(vec.begin(), vec.end(), 13) == vec.size());

  // copy construction should be preserved
  vec.push_back(7);
  assert(7 == vec.back());

  return 0;
}

此解决方案将取决于特定供应商的编译器和放大器的紧密程度。 STL的std::vector实现符合c ++ 11。

3 个答案:

答案 0 :(得分:6)

不要在容器周围使用包装器,而是考虑在元素类型周围使用包装器:

template <typename T>
struct uninitialized
{
    uninitialized() { }
    T value;
};

答案 1 :(得分:5)

我认为问题归结为容器对元素执行的初始化类型。比较:

T * p1 = new T;   // default-initalization
T * p2 = new T(); // value-initialization

标准容器的问题在于它们将默认参数初始化为值,如resize(size_t, T = T())中所示。这意味着没有优雅的方法来避免值初始化或复制。 (类似于构造函数。)

即使使用标准分配器也不起作用,因为它们的中心construct()函数接受一个变为值初始化的参数。您更需要的是使用默认初始化的construct()

template <typename T>
void definit_construct(void * addr)
{
  new (addr) T;  // default-initialization
}

这样的东西不再是一个符合标准的分配器了,但你可以围绕这个想法建立自己的容器。

答案 2 :(得分:1)

我不相信这可以通过包装矢量(适用于所有类型)来实现,除非您在每次添加和删除操作上调整矢量大小。

如果您可以放弃包装STL容器,则可以通过在堆上保留char数组并对要构造的每个对象使用放置new来实现此目的。通过这种方式,您可以逐个控制对象的构造函数和析构函数的确切控制。