Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Destroy object in std::vector

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>>.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading