destructor和allocator :: destroy有什么区别

时间:2020-08-10 14:43:21

标签: c++ memory vector destructor

上了这个课:

template<class T>
class Vec
{
public:
    typedef T* iterator;
    typedef T* const const_iterator;
    typedef T value_type;

    Vec() {
        create();
    }
    explicit Vec(size_t n, const T& val = T()) {
        create(n, val);
    }
    void clear() //here, I cannnot destroy nither by alloc.destroy, nor i->~T()
    {
        if (data)
        {
            iterator i = avail;
            while (i != data)
            {
                alloc.destroy(--i); //or i->~T()
            }
        }
        avail = data;
    }
    ...
private:
    iterator data;
    iterator avail;
    iterator limit;

    std::allocator<T> alloc;
    void create();
    void create(size_t n, const T &val);
    ...

现在,我将在主文件中使用clear functino(std::allocator<T>::destroy的版本,而不是析构函数):

#include "vec2.hpp"
#include <iostream>
#include <string>

using namespace std;

int main()
{
    Vec<string> v(3, "abc");
    v.clear();
    cout << v[2] << endl;
}

1。) 现在,即使我已经清除了Vec类(对其中的所有元素执行析构函数),我仍然可以输出v[2] -> "abc",即使认为该字符串应该执行析构函数,因此也为空字符串。

2。)我应该使用alloc.destroy(i)i的{​​{1}},还是应该使用T*

0 个答案:

没有答案
相关问题