在lambdas中 move std::shared_ptr
时,我遇到一个奇怪的问题。我不确定是否是错误,因为我可以使用g++ v6.3和clang++ v3.9复制。
当我编译并运行以下程序时:
#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
会使执行打印出我无法解释的内容:1 0x55a49e601c30 1
3 0x55a49e601c30 3
2 0x55a49e601c30 2
因此,看来
std::move(move)
在lambda内执行时,实际上并没有导致shared_ptr
move ,也没有防止其引用计数器增加。同样,我可以使用clang++和g++来重现此内容。
那怎么可能?
最佳答案
默认情况下,在lambda中捕获的变量ptr
是const,即ptr
的类型是const std::shared_ptr<int>
。std::move
无法移出const对象,因此创建了一个副本。
如果您确实要 move 它,则必须允许ptr
可变:
auto lambda = [ptr]() mutable {
// ^~~~~~~
关于c++11 - std::move与std::shared_ptr在lambda中 move ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43319352/