【问题标题】:Why don't I need to std::move to a std::bind'ed function?为什么我不需要 std::move 到 std::bind'ed 函数?
【发布时间】:2012-01-05 16:45:37
【问题描述】:

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

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> >)'

【问题讨论】:

    标签: c++ g++ c++11 rvalue-reference stdbind


    【解决方案1】:

    使用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&lt;TiD&gt;::value的值j不为零,则参数为std::forward&lt;Uj(uj)&gt;,其类型ViUj&amp;&amp;

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

    【讨论】:

    • 有趣!我正在处理一个更复杂的案例,结果似乎也取决于周围代码的一些副作用。
    • 是的,似乎在 GCC 4.7 中已修复。
    • 顺便问一下,我如何找到您对 [func.bind.bind]/p10/b3 的引用?谷歌搜索不好。
    • @Andres:[func.bind.bind] 是 N3290 的 §20.8.9.1.2。下载标准、N3242 或工作草案的副本,并查找通用实用程序、功能对象。
    • @AndresJaanTack:寻找最新的 c++11 标准草案,您可以找到并在该文档中搜索 [func.bind.bind]
    猜你喜欢
    • 2012-07-28
    • 2017-06-11
    • 2015-05-10
    • 2014-02-16
    • 2016-12-05
    • 2019-07-09
    • 1970-01-01
    • 2011-03-16
    相关资源
    最近更新 更多