简体   繁体   中英

Custom Vector pop_back function

So I'm trying to implement a pop_back() function for my Vector class, but I'm not getting the expected results:

Here's my current function:

template <typename T>
void Vector<T>::pop_back() {
    if(vsize > 0){
        array[vsize].~T();
        --vsize;
    }
}

Why doesn't this delete the last element in the array?

Here's my .h :

template <typename T>
class Vector {

public:

    Vector();
    ~Vector();
    void push_back(const T &e);
    int size() const;
    void pop_back();
    void allocate_new();
    T operator[](int index);

private:

    Vector(const Vector<T> & v);
    Vector<T> & operator=(const Vector<T> &);
    int vsize;
    int capacity;
    T* array;

};

Calling the destructor of an object in an array won't do anything to the array other than putting the element of the array into a funny state. In particular, if do something like this:

T* array = new T[2];
array[1].~T();
delete[] array; // ERROR: double destruction

you can't really get rid of the array at all without first restoring the destroyed array element.

The way a "real" implementation deals with the situation is to allocate raw memory, eg, using void* memory = operator new[](size); (with a suitbale size ) or, if it is a standard C++ library container, using the appropriate allocator functions. The container than constructs and destructs objects in the memory as needed. The actual representation in the destroyed memory may still not really change as most destructors just get rid of any resources held and leave the bits in the object otherwise unchanged, giving the appearance as if there is a life object in the memory although it is not.

数组的最后一个元素将在array[vsize - 1]

You shouldn't call the destructor of an object unless it was created using a placement-new expression. What you should instead do is reduce the size and leave the actual object untouched. Unless it has dynamic-storage duration, in which case call delete / delete[] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM