如何解决std::bind 和/或 std::forward
我觉得下面的代码无法编译很令人困惑
#include <functional>
class Mountain {
public:
Mountain() {}
Mountain(const Mountain&) = delete;
Mountain(Mountain&&) = delete;
~Mountain() {}
};
int main () {
Mountain everest;
// shouldn't the follwing rvalues be semantically equivalent?
int i = ([](const Mountain& c) { return 1; })(everest);
int j = (std::bind([](const Mountain& c) {return 1;},everest))();
return 0;
}
编译错误是:
$ g++ -std=c++20 test.cpp -o test
In file included from test.cpp:1:
/usr/bin/../lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/functional:486:26: error: no
matching constructor for initialization of 'tuple<Mountain>'
: _M_f(std::move(__f)),_M_bound_args(std::forward<_Args>(__args)...)
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/bin/../lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/functional:788:14: note: in
instantiation of function template specialization 'std::_Bind<(lambda at test.cpp:14:22)
(Mountain)>::_Bind<Mountain &>' requested here
return typename __helper_type::type(std::forward<_Func>(__f),^
test.cpp:14:17: note: in instantiation of function template specialization 'std::bind<(lambda at
test.cpp:14:22),Mountain &>' requested here
int j = (std::bind([](const Mountain& c) {return 1;},everest))();
^
...
所以 std::bind
偷偷地尝试复制 everest
,即使 lambda 只想要对它的引用。我是在反对一个没人关心的奇怪的边缘情况(例如,总是可以通过 lambda 捕获对 everest
的引用)还是有理由?如果基本原理是在 everest
被销毁后 bind 保护我免于调用 lambda,那么是否有不安全的 bind 版本不会这样做?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。