且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

std :: move与std :: shared_ptr在lambda中移动

更新时间:2023-11-11 13:02:46

默认情况下,lambda中捕获的变量 ptr 是const,即 ptr 的类型为 const std :: shared_ptr< int> .

The captured variable ptr in a lambda is by default const, i.e. the type of ptr is const std::shared_ptr<int>.

std :: move 无法移出const对象,因此创建了副本.

std::move cannot move out const objects, so a copy is created instead.

如果您确实要移动它,则必须允许 ptr 是可变的:

If you really want to move it, the ptr must be allowed to be mutable:

auto lambda = [ptr]() mutable {
//                    ^~~~~~~