我阅读了boost asio http服务器示例代码(参见http://www.boost.org/doc/libs/1_54_0/doc/html/boost_asio/example/cpp11/http/server/connection.cpp)并找到auto self(shared_from_this());变量是已在捕获范围([this, self])中使用.但自变量未在lambda函数中使用.那么这样做有什么好处?
我正在学习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;
Run Code Online (Sandbox Code Playgroud)
尝试1 - 不起作用,因为unique_ptr没有复制构造函数.c ++ 0x没有指定移动语法.
std::for_each(arr.begin(), arr.end(), [p](int& i) { i+=*p; });
Run Code Online (Sandbox Code Playgroud)
尝试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))
);
Run Code Online (Sandbox Code Playgroud)
编译器抱怨说 'result' : symbol is neither a class template nor a function template.
这个练习的主要目的是了解如何在lambda中捕获可移动变量,该lambda被缓存以供以后使用.