为什么我不需要 std::move to std::bind'ed 函数?

Why don't I need to std::move to a std::bind'ed function?

本文关键字:std ed 函数 to 不需要 move 为什么 bind      更新时间:2023-10-16

假设我有一个函数,取一个右值引用:

void whatever (std::unique_ptr<int>&&) {
    // Nothing!
}

我把它的一个参数绑定到一个占位符上。

auto f = std::bind(&whatever, _1);

我尝试了这样的调用,结果与我预期的相反。

std::unique_ptr<int> nothing;
f(std::move(nothing));  // Fails to compile!
f(nothing);             // Works, but seems wrong!

这是编译器错误吗?或者,工作调用是否是不安全的代码?或者为什么我不必将这个指针std::move放入绑定函数中?

顺便说一下,gcc4.4的编译错误是:

test.cxx:14: error: no match for call to '(std::_Bind<void (*(std::_Placeholder<1>))(std::unique_ptr<int, std::default_delete<int> >&&)>) (std::unique_ptr<int, std::default_delete<int> >)'

使用libc++时,我得到的结果正好相反。

std::unique_ptr<int> nothing;
f(std::move(nothing));  // Works!
f(nothing);             // Fails to compile!

我认为这是一个gcc4.4错误。[func.bind.bind]/p10/b3描述了这种情况:

  • 如果is_placeholder<TiD>::value的值j不为零,则变元为std::forward<Uj(uj)>,其类型ViUj&&

这可能会在最近的gcc中得到修复(我不知道)。