mercredi 28 juillet 2021

How to correctly copy a lambda with a reference capture?

Ok so I ran into a problem when implementing a c# property like system in c++ (see: https://stackoverflow.com/a/68557896/3339838).

Consider the following example:

struct TransformCmp
{
PropertyDelGetSet<vec3> position =
    PropertyDelGetSet<vec3>(
        [&]() -> const vec3& { return m_position; },
        [&](const vec3& val) { m_position = val; m_dirty = true; });

private:
    vec3 m_position = vec3(0);
}

If/when the instance of the TransformCmp is copied/moved (e.g. if it was stored in std::vector and resize was called), the reference capture is now invalid.

The question is how do I make sure when the copy/move happens that I also update the reference capture?

I've tried implementing a copy constructor for the Property classes but I ran into the same issue, probably because I didn't do it correctly. Any ideas?

Aucun commentaire:

Enregistrer un commentaire