Destroy object in std::vector

  allocator, c++, memory

I wan’t to be able to destroy any object without loosing memory:

from:
`--------+--------+--------`
| item 1 | item 2 | item 3 |
`--------+--------+--------`
to:
`--------+--------+--------`
| item 1 | empty  | item 3 |
`--------+--------+--------`

Used std::vector<T>::erase is what comes closest to it, but it doesn’t allow me to acces the the old "memory":

`--------+--------`
| item 1 | item 3 |
`--------+--------`

I tryed to use std::allocator_traits<T>, but i didn’t figured out how to use it to compile:

using allocator = std::allocator_traits<type>;
using alloc_type = std::allocator_traits<type>::allocator_type;

class MyClass {
    public:
        MyClass(int i) : m_i(i) {}
        ~MyClass() = default;
    private:
        int m_i;
};

int main()
{

    std::vector<MyClass, allocator> vec;

    vec.emplace_back(0);
    // destroy the object but don't rearrange
    allocator::destroy(alloc_type, std::addressof(vec[0]));
}

This code doesn’t compile

Source: Windows Questions C++

LEAVE A COMMENT