简体   繁体   English

自定义矢量pop_back函数

[英]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: 所以我正在尝试为我的Vector类实现pop_back()函数,但没有得到预期的结果:

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 : 这是我的.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); “实际”实现处理情况的方式是分配原始内存,例如,使用void* memory = operator new[](size); (with a suitbale size ) or, if it is a standard C++ library container, using the appropriate allocator functions. size合适),或者,如果它是标准C ++库容器,则使用适当的分配器函数。 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[] . 除非它具有动态存储持续时间,否则将调用delete / delete[]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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