0

I'm new to C++ and am working on an existing codebase, and am trying to figure out how to pass an r-value ref unique pointer into a lambda and transfer ownership properly.

Currently, we have:

void MyClass::onResponse(uniq_ptr<Foo>&& response) {
    parent_.doSomething(std::move(response));
}

I need to modify this to do some stuff (fire a timer, basically) on the main thread using a function postToMainThread which takes a lambda, and then call doSomething as before. Posting to main thread with a dummy response works fine, but when I try to pass/move the lambda through, I get a segfault as something on the other side tries to take ownership of the response:

void MyClass::onResponse(uniq_ptr<Foo>&& response) {
    postToMainThread([this, &response]() {
        // Do some stuff that must be on main thread
        parent_.doSomething(std::response);
    }
}

I've seen a number of examples that use postToMainThread([this, response = std::move(response)]() {... but that does not compile due to a copy constructor on unique pointer error. I gather I need to transfer ownership of the response, but I'm not sure how.

nflacco
  • 4,972
  • 8
  • 45
  • 78

1 Answers1

1

Ok, figured it out. I added a response_ property to MyClass, and moved it in MyClass::onResponse(). That in turn fired the post and timer, which called a new MyClass::XXX(). This in turn performed parent_.doSomething(std::move(response_)) with the stored response. Whew!

nflacco
  • 4,972
  • 8
  • 45
  • 78