使用std :: async的奇怪行为

时间:2014-04-22 04:38:30

标签: c++ gcc c++11 stdasync

请考虑以下示例代码:

#include <future>
#include <array>
#include <cassert>

typedef std::array<int, 5> foo_t;

foo_t* bar(foo_t& foo) {
   return &foo;
}

int main() {
   foo_t foo;
   auto a = std::async(bar, foo);
   auto b = std::async(bar, foo);
   assert(a.get() == b.get());
   return 0;
}

GCC 4.6.3对此进行了编译,没有任何投诉。但是,这在运行时失败:

test: test.cpp:15: int main(): Assertion `a.get() == b.get()' failed.
Aborted (core dumped)
然而,

GCC 4.8.2拒绝编译文件:

In file included from /usr/local/include/c++/4.8.2/future:38:0,
                 from test.cpp:1:
/usr/local/include/c++/4.8.2/functional: In instantiation of 'struct std::_Bind_simple<std::array<int, 5ul>* (*(std::array<int, 5ul>))(std::array<int, 5ul>&)>':
/usr/local/include/c++/4.8.2/future:1525:70:   required from 'std::future<typename std::result_of<_Functor(_ArgTypes ...)>::type> std::async(std::launch, _Fn&&, _Args&& ...) [with _Fn = std::array<int, 5ul>* (&)(std::array<int, 5ul>&); _Args = {std::array<int, 5ul>&}; typename std::result_of<_Functor(_ArgTypes ...)>::type = std::array<int, 5ul>*]'
/usr/local/include/c++/4.8.2/future:1541:36:   required from 'std::future<typename std::result_of<_Functor(_ArgTypes ...)>::type> std::async(_Fn&&, _Args&& ...) [with _Fn = std::array<int, 5ul>* (&)(std::array<int, 5ul>&); _Args = {std::array<int, 5ul>&}; typename std::result_of<_Functor(_ArgTypes ...)>::type = std::array<int, 5ul>*]'
test.cpp:13:30:   required from here
/usr/local/include/c++/4.8.2/functional:1697:61: error: no type named 'type' in 'class std::result_of<std::array<int, 5ul>* (*(std::array<int, 5ul>))(std::array<int, 5ul>&)>'
       typedef typename result_of<_Callable(_Args...)>::type result_type;
                                                             ^
/usr/local/include/c++/4.8.2/functional:1727:9: error: no type named 'type' in 'class std::result_of<std::array<int, 5ul>* (*(std::array<int, 5ul>))(std::array<int, 5ul>&)>'
         _M_invoke(_Index_tuple<_Indices...>)
         ^

这似乎是一个libstdc ++问题。

所以我的问题是: 1 - GCC应拒绝此代码,还是标准中有一些我不知道的内容。 2 - 断言是否应该失败?预期的行为是,采用相同引用的异步函数应该引用同一个对象,但看起来副本是异步任务的本地副本。

我尝试使用clang编译,但它与4.8.2具有相同的编译错误问题(因为它共享相同的libstdc ++),并且它无法编译4.6.3库头。

1 个答案:

答案 0 :(得分:5)

  1. 是的,gcc应拒绝此代码。 std::async复制参数并将它们转发为rvalues。您不能将右值绑定到左值引用,因此失败。如果您想通过引用传递使用std::ref(foo)。在此特定示例中,对std::async(bar,foo)的调用基本上执行以下操作:

    template<typename F>
    future<foo_t*> async(F& func,foo_t& arg){
        F func_copy(func);
        foo_t arg_copy(arg);
        // on background thread
        internal_set_future_result(func_copy(std::move(arg_copy)));
        return ...;
    }
    
  2. 如果您使用std::ref(foo),则断言不应失败。如果代码没有编译,那么这是一个没有实际意义的点。