C++ Suppress Automatic Initialization and Destruction

前端 未结 5 1820
予麋鹿
予麋鹿 2021-01-03 02:15

How does one suppress the automatic initialization and destruction of a type? While it is wonderful that T buffer[100] automatically initializes all the elemen

5条回答
  •  情话喂你
    2021-01-03 02:38

    You may want to look into boost::optional

    template  struct tovoid { typedef void type; };
    
    template 
    struct ArrayStorage {
      typedef T type;
      static T &get(T &t) { return t; }
    };
    
    template 
    struct ArrayStorage::type> {
      typedef boost::optional type;
      static T &get(boost::optional &t) {
        if(!t) t = boost::in_place();
        return *t;
      }
    };
    
    template 
    class Array
    {
    public:
        T &operator[](std::ptrdiff_t i) {
          return ArrayStorage::get(m_buffer_[i]);
        }
    
        T const &operator[](std::ptrdiff_t i) const {
          return ArrayStorage::get(m_buffer_[i]);
        }
    
        mutable typename ArrayStorage::type m_buffer_[KCount];
    };
    

    A specialization is done for class type that wraps them into an optional, thus calling the constructor/destructor lazily. For non-class types, we don't need that wrapping. Not wrapping them means we can treat &a[0] as a contiguous memory area and pass that address to C functions that want an array. boost::in_place will create the class types in-place, without using a temporary T or its copy constructor.

    Not using inheritance or private members allow the class to stay an aggregate, allowing a convenient form of initialization

    // only two strings are constructed
    Array array = { a, b };
    

提交回复
热议问题