问题描述
我觉得下面的代码无法编译很令人困惑
#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 (将#修改为@)