C++ Suppress Automatic Initialization and Destruction

前端 未结 5 1821
予麋鹿
予麋鹿 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:37

    You can create the array as array of chars and then use placement new to create the elements when needed.

    template 
    class Array
    {
    private:
        char m_buffer[KCount*sizeof(T)]; // TODO make sure it's aligned correctly
    
        T operator[](int i) {
            return reinterpret_cast(m_buffer[i*sizeof(T)]);
        }
    

    After re-reading your question it seems that you want a sparse array, this sometimes goes by the name of map ;o) (of course the performance characteristics are different...)

    template 
    class SparseArray {
        std::map m_map;
    public:
        T& operator[](size_t i) {
            if (i > KCount)
                throw "out of bounds";
            return m_map[i];
        }
    

提交回复
热议问题