lambdas
question:
の移動キャプチャ)たとえば、
std::unique_ptrmyPointer(new int); std::function example = [std::move(myPointer)] { *myPointer = 4; };
回答:
一般化されたラムダキャプチャC 14
で、一般化されたラムダキャプチャにより移動キャプチャが可能になります。このコードが有効になりました:
using namespace std; auto u = make_uniquenamespace std; auto u = make_unique(some, parameters); go.run([u = move(u)] { do_something_with(u); });
オブジェクトをラムダから別の関数に移動するには、ラムダを可変化可能にします:
using namespace std; auto u = make_uniquego.run([u = move(u)] mutable {do_someething_with(std :: move(u));}) 11(some, parameters); go.run([u = move(u)] { do_something_with(u); });
ヘルパー関数、make_rrefは、移動キャプチャを促進できます。その実装は次のとおりです
#include
make_rrefのテストケース:
#include#include #include template struct rref_impl { rref_impl() = delete; rref_impl(T&& x) : x{std::move(x)} {} rref_impl(rref_impl& other) : x{std::move(other.x)}, isCopied{true} { assert(other.isCopied == false); } rref_impl(rref_impl&& other) : x{std::move(other.x)}, isCopied{std::move(other.isCopied)} { } rref_impl& operator=(rref_impl other) = delete; T& operator&&() { return std::move(x); } private: T x; bool isCopied = false; }; template rref_impl make_rref(T&& x) { return rref_impl {std::move(x)}; }
エミュレート一般化されたラムダキャプチャのc #include
using namespace std; auto u = make_uniqueキャプチャは次のように実装されます:(some, parameters); go.run([u = move(u)] { do_something_with(u); });
#include
。
免責事項: 提供されるすべてのリソースの一部はインターネットからのものです。お客様の著作権またはその他の権利および利益の侵害がある場合は、詳細な理由を説明し、著作権または権利および利益の証拠を提出して、電子メール [email protected] に送信してください。 できるだけ早く対応させていただきます。
Copyright© 2022 湘ICP备2022001581号-3