Explicit Destructor

The following code is used to illustrate my question.

template<class T>
class array<T>
{
 public:
    // constructor
    array(cap = 10):capacity(cap)
    {element = new T [capacity]; size =0;}

    // destructor
    ~array(){delete [] element;}
    void erase(int i);
    private:
      T *element;
      int capacity;
      int size;
};



template<class T>
void class array<T>::erase(int i){
     // copy
     // destruct object
    element[i].~T();  ////
    // other codes
} 

If I have array<string> arrin main.cpp. When I use erase(5), the object is element[5]destroyed, but the space element[5]will not be freed, can I just use element[5] = "abc"a new value to place it here? or do I need to use the new placement to place the new value in space element [5]?

, arr<string> , delete [] element. , , , . element[5], ( arr) element[5]? , , ? , , , .

:

(1)I have to use placement new if I explicitly call destructor.

(2) repeatedly destructing object is defined as undefined behavior which may be accepted in most systems but should try to avoid this practice.

+3
2

-:

new (element + 5) string("abc");

element[5] = "abc"; operator= element[5], , undefined.

, arr<string> , delete [] element.

: , (, elements[5] ). undefined.

std::allocator . . ++.

+6

, , UD ....

erase() - - , + , .. < > delete[] element, , , , , .., , , .

, , - new - , , - , .

T, , :

struct T
{
    T() : p_(new int) { }
    ~T() { delete p_; }
    int* p_;
};

p_, new, erase(), ~array(). , p_ , delete ~array() - 0, , new. new, , p_, .

, , , : , p_ 0 delete. , , , , - , , UD .

+2

Source: https://habr.com/ru/post/1789894/


All Articles