C++核心準(zhǔn)則F.53:非局部使用變量時(shí)避免使用值捕捉

F.53: Avoid capturing by reference in lambdas that will be used nonlocally, including returned, stored on the heap, or passed to another thread
如果捕捉的變量可以能被非局部使用,則應(yīng)避免在lambda表達(dá)式中使用引用形式的捕捉。非局部使用包括返回,保存在堆中,或者傳遞給其他線(xiàn)程。
Reason(原因)
Pointers and references to locals shouldn't outlive their scope. Lambdas that capture by reference are just another place to store a reference to a local object, and shouldn't do so if they (or a copy) outlive the scope.
指向局部變量的指針和引用的生命周期不應(yīng)該長(zhǎng)于它們的作用域。通過(guò)引用捕捉變量的lambda表達(dá)式只是另外一個(gè)保存指向局部變量的引用的場(chǎng)所,如果這個(gè)lambda表達(dá)式(或拷貝)的生命周期超過(guò)作用域時(shí)不應(yīng)該使用引用形式的變量捕捉。
Example, bad(反面示例)
int local = 42;// Want a reference to local.// Note, that after program exits this scope,// local no longer exists, therefore// process() call will have undefined behavior!thread_pool.queue_work([&]{ process(local); });Example,?goodint?local?=?42;// Want a copy of local.// Since a copy of local is made, it will// always be available for the call.thread_pool.queue_work([=]{ process(local); });
(Simple) Warn when capture-list contains a reference to a locally declared variable
(簡(jiǎn)單)當(dāng)捕捉列表中包含本地聲明的變量時(shí)報(bào)警。
(Complex) Flag when capture-list contains a reference to a locally declared variable and the lambda is passed to a non-
constand non-local context(復(fù)雜)在捕捉列表中包含指向局部聲明的變量而且lambda表達(dá)式被傳遞給非常量或非局部上下文時(shí)做出提示。
???? 譯者注:第一種情況容易實(shí)現(xiàn)但并不完美。
覺(jué)得本文有幫助?請(qǐng)分享給更多人
關(guān)注【面向?qū)ο笏伎肌浚刻烨斑M(jìn)一小步
有任何疑問(wèn),歡迎留言提問(wèn)或討論
面向?qū)ο笤O(shè)計(jì),面向?qū)ο缶幊?,面向?qū)ο笏伎迹?/p>
