mercredi 22 mai 2019

How to use std::vector for classes with handles

I have definded the following class witch creates and frees an opaque object (e.g. an operating system handle)

class A
{
public:

    A(...)
    {
        allocateHandle(&h);
    }

    ~A()
    {
        freeHandle(h);
    }

    SomeHandle h;
}

When creating and resizing std::vector of A, the program crashes.

std::vector<A> vec;
vec.reserve(2);

vec.emplace_back(...);
vec.emplace_back(...);
vec.emplace_back(...); //crash

When std::vector reallocates memory, it calls the move constructor on all the objects, thus also moving the handle in A (which is basically an integer).

However, it also calls the destructor on the old object, which calls freeHandle(), thus it frees the memory behind the handle, that the new object still has, which becomes invalid and causes the crash.

How should I implement the move-constructor, so that the newly created object doesn't become invalid, when the old one is deleted?

Aucun commentaire:

Enregistrer un commentaire