0

I'm trying to create a thread wrapper that will execute a lambda function with N parameters INSIDE a __try / __except as defined here: https://learn.microsoft.com/en-us/cpp/cpp/structured-exception-handling-c-cpp?view=vs-2019

The application is not supposed to recover from the exception. It will terminate right after calling a Windows function to generate a Crash Dump, just like here: https://learn.microsoft.com/en-us/windows/win32/dxtecharts/crash-dump-analysis

Since this is a thread wrapper, I must make it as generic as possible, allowing for any types of lambda signatures (as long as they all return void).

class MiniThread {
public:
    template<typename F, typename... Args>
    void run(F func, Args... args)
    {
        if (m_thread != nullptr)
            join();

        m_thread = new std::thread([&]() {
            _run(func, std::forward<Args>(args)...);
        });

        m_started = true;
    }

    bool started() const { return m_started; }
    void join();

    ~MiniThread();
private:
    template<typename F, typename... Args>
    void _run(F func, Args... args)
    {
        __try
        {
            func(std::forward<Args>(args)...);
        }
        __except (CrashDump::GenerateDump(GetExceptionInformation()))
        {
            // TODO: log.
        }
    }

    std::thread *m_thread = nullptr;
    bool m_started = false;
};

My test use of it is as follow:

// any parameters/arguments should work.
auto lambda = [this](std::string whatever, std::promise<uint> && p) {
    // anything should work here.
};

std::promise<uint> promise;
std::string whatever = "whatever";
MiniThread thread;
thread.run(lambda, promise);

Unfortunately, the attempt of building this on Visual Studio 2017 causes the following error:

Error C2712 Cannot use __try in functions that require object unwinding

I have tried "burying" code deeper into a stack of function calls, but I'm guessing the std::forward of the packed variadic args is not allowing me.

Please understand that I REALLY don't need the application to recover from the crash. Just for it to generate a crash dump and terminate.

Alexandre Severino
  • 1,563
  • 1
  • 16
  • 38
  • You cannot use SEH exception handlers in functions, that have to construct some non-trivial objects (e.g. vector, lambdas, etc.). I think, you should try to avoid calling constructors - for example get pointers to all parameters and use them in low-level function, that can use `__try`-block – Georgy Firsov Apr 14 '20 at 19:48
  • I'm aware that I can get around this by going with only pointers. But is there a way I can convert all my arguments into pointers just before the `__try` block starts? – Alexandre Severino Apr 14 '20 at 20:01

0 Answers0