1

I need object to be alive from some point in code, until some task starts executing. Like in example:

shared_ptr<FromThisPointToTaskStart> ftptts = make_shared<FromThisPointToTaskStart>();
. . .
runningTask.then([ftptts](task<void> task)
{
    . . .
    try{
        // Decrementing reference and deallocating object if ref count == 0;
        ftptts = nullptr;
        task.get();
   }
}
// decrementing reference count so that it lives untill task starts
ftptts = nullptr;

The problem is that capture list catches this as constant and I cannot change it. What is the right way to do what I want? Should I pass it like [&ftptts] ?

Thanks!

J. Doe
  • 33
  • 1
  • 4
  • 4
    Making the [lambda mutable](http://en.cppreference.com/w/cpp/language/lambda) should get you the behaviour you're looking for. – G.M. Jul 06 '17 at 09:48
  • And what if I have multuple parameters in capture list, how would I make just this one mutable and not others? – J. Doe Jul 06 '17 at 10:01
  • @J.Doe This seems to have some info: https://stackoverflow.com/questions/3772867/lambda-capture-as-const-reference – Galik Jul 06 '17 at 10:11
  • Does it really need to be a `lambda`? If not then why not just use `std::bind` with a function whose parameters have the necessary `const` qualifiers. – G.M. Jul 06 '17 at 12:53

1 Answers1

2

I have tested your code, and here are the findings:

  1. Passing std::shared_ptr as non reference will assume that you won't change that variable, but its lifetime will be prolonged until end of .then{} block even thought you don't use it in that block, and you set it to nullptr in outside scope.

  2. Passing std::shared_ptr as reference there will deallocate object when you set it to nullptr in the surrounding scope, so after you set it to nullptr again in then block you will get an exception.

  3. The solution you are asking for is adding mutable, though this will make all other parameters mutable as well.

    runningTask.then([ftptts](task<void> task) mutable{...}
    
MegaTron
  • 102
  • 6
  • "Passing std::shared_ptr as non reference will assume that you won't change that variable" This statement is wrong. passing as const reference or generally as const would allow the code to make that assumption. – KeyC0de Sep 24 '19 at 12:28