visual studio implementation of “move semantics” and “rvalue reference”

后端 未结 2 453
终归单人心
终归单人心 2020-12-10 19:14

I came across a Youtube video on c++11 concurrency (part 3) and the following code, which compiles and generates correct result in the video.

However, I got a compi

2条回答
  •  盖世英雄少女心
    2020-12-10 19:34

    This appears to be a bug in MSVC2012. (and on quick inspection, MSVC2013 and MSVC2015)

    thread does not use perfect forwarding directly, as storing a reference to data (temporary or not) in the originating thread and using it in the spawned thread would be extremely error prone and dangerous.

    Instead, it copies each argument into decay_t's internal data.

    The bug is that when it calls the worker function, it simply passes that internal copy to your procedure. Instead, it should move that internal data into the call.

    This does not seem to be fixed in compiler version 19, which I think is MSVC2015 (did not double check), based off compiling your code over here

    This is both due to the wording of the standard (it is supposed to invoke a decay_t with decay_t... -- which means rvalue binding, not lvalue binding), and because the local data stored in the thread will never be used again after the invocation of your procedure (so logically it should be treated as expiring data, not persistent data).

    Here is a work around:

    template
    struct thread_rvalue_fix_wrapper {
      F f;
      template
      auto operator()(Args&...args)
      -> typename std::result_of::type
      {
          return std::move(f)( std::move(args)... );
      }
    };
    template
    thread_rvalue_fix_wrapper< typename std::decay::type >
    thread_rvalue_fix( F&& f ) { return {std::forward(f)}; }
    

    then

    thread th(thread_rvalue_fix(&toSin), /*std::ref(list)*/std::move(list));
    

    should work. (tested in MSVC2015 online compiler linked above) Based off personal experience, it should also work in MSVC2013. I don't know about MSVC2012.

提交回复
热议问题