문제

I want to submit a handle but I only want it to be executed if a shared pointer is still valid:

// elsewhere in the class:
std::shared_ptr<int> node;

// later on:
const std::weak_ptr<int> slave(node); // can I do this in the capture clause somehow?
const auto hook = [=]()
{
  if (!slave.expired())
    //do something
  else
    // do nothing; the class has been destroyed!
};

someService.Submit(hook); // this will be called later, and we don't know whether the class will still be alive

Can I declare slave within the capture clause of the lambda? Something like const auto hook = [std::weak_ptr<int> slave = node,=]().... but unfortunately this doesn't work. I would like to avoid declaring the variable and then copying it (not for performance reasons; I just think it would be clearer and neater if I could create whatever the lambda needs without polluting the enclosing scope).

도움이 되었습니까?

해결책

You can do this using generalized lambda captures in C++14:

const auto hook = [=, slave = std::weak_ptr<int>(node)]()
{
    ...
};

Here's a live example. Note that since there are no parameters or explicit return type, the empty parameter list (()) can be left out.

다른 팁

As mentioned by chris this is possible in C++14.

If you are willing to modify the captured value simply add mutablespecifier. Here is an example which fills a vector from zero to the length of the vector.

#include <iostream>
#include <vector>
#include <algorithm>


int main()
{
    std::vector<int> container(10);

    std::generate(container.begin(), container.end(), [n = 0]() mutable { return n++; });

    for (const auto & number : container)
    {
        std::cout << number << " ";
    }

    std::cin.ignore();

    return 0;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top