std :: move与std :: shared_ptr在lambda中移动 [英] std::move with std::shared_ptr in lambda

查看:96
本文介绍了std :: move与std :: shared_ptr在lambda中移动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在lambdas中移动 std :: shared_ptr s时,我遇到一个奇怪的问题.我不确定这是否是错误,因为我可以使用g ++ v6.3和clang ++ v3.9进行复制.

I have a strange issue when moving std::shared_ptrs in lambdas. I am not sure if it is a bug or not, as I can reproduce with g++ v6.3 and clang++ v3.9.

当我编译并运行以下程序时:

When I compile and run the following program:

#include <iostream>
#include <memory>

void f(std::shared_ptr<int> ptr) {
  std::cout << 3 << " " << ptr.get() << std::endl;
}

int main() {
  auto ptr = std::make_shared<int>(42);
  std::cout << 1 << " " << ptr.get() << std::endl;
#ifdef LAMBDA
  auto lambda = [ptr]() {
#endif
    f(std::move(ptr));
    std::cout << 2 << " " << ptr.get() << std::endl;
#ifdef LAMBDA
  };
  lambda();
#endif
}

使用命令 c ++ -std = c ++ 14 -o test main.cpp&&./test 产生类似

1 0x55a49e601c30 1
3 0x55a49e601c30 1
2 0 0

但是,将编译命令更改为 c ++ -std = c ++ 14 -o test main.cpp -DLAMBDA 会使执行打印出我无法解释的内容:

However, changing the compilation command to c++ -std=c++14 -o test main.cpp -DLAMBDA makes the execution print something I cannot explain:

1 0x55a49e601c30 1
3 0x55a49e601c30 3
2 0x55a49e601c30 2

因此,看来 std :: move(move)在lambda中执行时,实际上并没有导致 shared_ptr 移动,也没有移动防止其参考计数器增加.

So, it appears that the std::move(move), when performed inside a lambda, does not actually cause the shared_ptr to be moved, nor does it prevent its reference counter to be incremented.

同样,我可以用clang ++和g ++复制它.

Again, I can reproduce this with clang++ and g++.

那怎么可能?

推荐答案

默认情况下,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 {
//                    ^~~~~~~

这篇关于std :: move与std :: shared_ptr在lambda中移动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆