C++ Suppress Automatic Initialization and Destruction

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

    If you want to be like vector, you should do something like this:

    template 
    class my_vector
    {
        T* ptr; // this is your "array"
        // ...
        public:
    
        void reserve(size_t n)
        {
            // allocate memory without initializing, you could as well use malloc() here
            ptr = ::operator new (n*sizeof(T)); 
        }
    
        ~my_vector()
        {
            ::operator delete(ptr); // and this is how you free your memory
        }
    
        void set_element(size_t at, const T& element = T())
        {
            // initializes single element
            new (&ptr[at]) T(element); // placement new, copies the passed element at the specified position in the array
        }
    
        void destroy_element(size_t at)
        {
            ptr[at].~T(); // explicitly call destructor
        }
    };
    

    This code is obviously for demonstration only, I have omitted my_vector's copy-constructor and any tracking on what's created and what not (calling destructor on a location you haven't called constructor for is probably undefined behavior). Also, STL's vector allocations and deallocations are abstracted away through the use of allocators (the second template argument of vector).

    Hope that helps

提交回复
热议问题