Copy-assigning C++ lambdas of the same type -
c++ lambdas have deleted copy-assignment operator. don't know why. limitation can worked around. don't feel it. wrong following approach? live code.
template <class t> void assign(t& dest, t&& val) { dest.~t(); new (&dest) t(std::forward<t>(val)); } auto make_lambda(int i) { return [v=std::make_shared<int>(i)] {std::cout << *v << "\n"; }; } int main() { auto 1 = make_lambda(1); assign(one, make_lambda(2)); one(); // prints 2 } there possibly 2 reasons can think of:
- construction may throw ,
destmain remain uninitialized , destroyed again later in main. double deletion. - destructor may throw if badly written library throws in destructor.
exception during construction can worked-around strong exception safety guarantee. consider assignv2:
template <class t> void assignv2(t& dest, const t& src) { static std::allocator<t> alloc; static typename std::aligned_storage<sizeof(t), alignof(t)>::type storage; std::memcpy(&storage, &dest, sizeof(t)); try { new (&dest) t(src); } catch(...) { std::memcpy(&dest, &storage, sizeof(t)); throw; } reinterpret_cast<t*>(&storage)->~t(); }
you don't need able (copy / move) assign lambdas.
class lambda { std::shared_ptr<int> v; public: explicit lambda(int i) : v(make_shared(i)) {} void operator()() { std::cout << *v << "\n"; } } auto make_lambda(int i) { return lambda(i); } or, memoization case, don't change memoise:
template <typename func> auto memoized_recursion(func func, cache c = cache::no_reclaim) { static std::unordered_map<func, decltype(memoise(func))> functor_map; if(cache::reclaim == c) return functor_map.insert_or_assign(func, memoize(func)).first->second; else return functor_map.insert(func, memoize(func)).first->second; }
Comments
Post a Comment