std::function bad memory access when creating a temporary

The lambda in the derived class captures this to the derived class, and shoves it into the base class's std::function.

This is a recipe for trouble.

What this means that, at the very least, the derived class must be fully Rule of 3 compliant, and implement, at the very least, a copy constructor and an assignment operator that meticulously reinstalls a new lambda, with a freshly-captured this that actually refers to the right instance of the derived class.

If you have a std::function member of a class, that captures its own this, and the class gets copied, the captured this does not get automatically updated to refer to the new instance of the class. C++ does not work this way. The new class's std::function's this still references the original instance of the class. And if an instance of a class is assigned from another instance of the class, guess what? The copied std::function's captured this still points to the copied-from instance of the class.

But I don't really see anything that the std::function does here that cannot be implemented by a garden-variety virtual function. Simply replace m_SDF by a virtual function, and this entire headache goes away.


Your bad memory access isn't due to the other variable, it's the this pointer of the temp object going out of scope.

You can fix it by capturing the SDF variables explicitly, like this:

LevelSetObject LevelSetObject::operator+(const LevelSetObject& other) const {
        LevelSetObject outObj;
        auto& SDF=this->m_SDF;
        auto& other_SDF=other.m_SDF
        outObj.m_SDF = [SDF, other_SDF]
            (double x, double y, double z) {
                return std::min(SDF(x, y, z), other_SDF(x, y, z));
            };
        return outObj;
    }