【发布时间】:2012-05-04 02:06:27
【问题描述】:
我正在学习 c++11 中的新功能并遇到了这个问题。我想通过将其移动到 lambda 中作为 for_each 的参数来捕获 unique_ptr。
设置:
std::array<int,4> arr = {1,3,5,6};
std::unique_ptr<int> p(new int); (*p) = 3;
尝试 1 - 不起作用,因为 unique_ptr 没有复制构造函数。 c++0x 没有指定 pass by move 语法。
std::for_each(arr.begin(), arr.end(), [p](int& i) { i+=*p; });
尝试 2 - 使用 bind 将 p 的移动副本绑定到采用 int& 的函数:
std::for_each(arr.begin(), arr.end(),
std::bind([](const unique_ptr<int>& p, int& i){
i += (*p);
}, std::move(p))
);
编译器抱怨'result' : symbol is neither a class template nor a function template.
本练习的主要目的是了解如何在 lambda 中捕获可移动变量以供以后使用。
【问题讨论】: