Destroy object in std::vector

Advertisements

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

>Solution :

You may not have destroyed objects in a vector. The vector will eventually destroy all elements and if any are already destroyed, then behaviour will be undefined.

Instead of a vector of MyClass, you could use a vector of std::aligned_storage and handle the construction and destruction of the MyClass objects onto the storage yourself. But I don’t recommend that because it can be quite challenging and trivial mistakes will lead to undefined behaviuour.

If your goal is to represent a "no value" state, then there is a template wrapper for such purpose in the standard library: std::optional. I.e. you could use std::vector<std::optional<MyClass>>.

Leave a ReplyCancel reply