I would like to write a class method that, if necessary, accepts a lambda to customize its behavior. So when I use this class, I wonder if I need to worry that the lambda itself is out of scope?
The lambda will not refer to any external vars, so I don’t worry about the scale of the vars, only about the area of the lambda itself that I would keep in the class.
Do I need to worry about how / where the lambda itself was created?
Links, outside of narrow situations, do not extend the life of the item you are linking to.
, , - undefined.
undefined lambda " this", . , , , .
this
, , -. , ( ), . ?
std::function<void()> , . , . std::function<void()> , , , .
std::function<void()>
, , RAII . . -
template <class T> class locker { private: mutable T m_t; // Copies the lambda here. mutable std::mutex m_m; public: locker( T t = T{} ) : m_t(t) {} template <typename F> auto operator()(F f) const -> decltype(f(m_t)) { std::lock_guard<mutex> _{m_m}; return f(t); } }; // usage locker<std::string> s; s([](string &s) { s += "foobar"; s += "barfoo"; });
- Lambda. lambdas, . , , . , , , , .