0

I am writing a function that creates a lambda that will later be used to call a function. This lambda captures a local variable by value, and it appears to be modifying the v-table as this happens.

The relevant code is below.

Promise<std::vector<std::reference_wrapper<Detection>>> HuntRegister::RunHunt(IN Hunt& hunt, 
                                                                              IN CONST Scope& scope OPTIONAL){

    return ThreadPool::GetInstance().RequestPromise<std::vector<std::reference_wrapper<Detection>>>(
        [hunt, scope]() mutable { 
            return hunt.RunHunt(scope); 
        });

The RequestPromise function just defers a function call until it can be executed later without modifying any part of it.

When I break before the return and look at hunt, this is what I see. Before capture by value

When I break inside the lambda and look at hunt, the v-table has changed. After capture by value

Based on the comments, it looks like the culprit here is object slicing. There's a bunch of solutions for preserving members, but I haven't found anything explaining how I can fix my issue. What can I do to ensure the v-table is preserved?

James McDowell
  • 2,668
  • 1
  • 14
  • 27
  • That is object slicing. When you copy the object it only copies the base part, cutting off all the information about the derived object that it actually is. That includes which functions it should dispatch to. – NathanOliver Jul 02 '20 at 16:52
  • Copying an object copies its member variables. The vtable is fixed for each type. – molbdnilo Jul 02 '20 at 16:56
  • That other question explaining object slicing explains how members can be preserved, but it says nothing about the vtable. How can I preserve the vtable here? – James McDowell Jul 02 '20 at 17:04
  • 1
    @JamesMcDowell When you create a new object of a new type when copying, you're gonna get a different vtable if the type being copied don't match the dynamic type of the original object. This is what object slicing does. – Guillaume Racicot Jul 02 '20 at 17:05

0 Answers0