Visual Studio 2013 C++ - Passing std::unique_ptr to a bound function

前端 未结 3 1752
走了就别回头了
走了就别回头了 2020-12-21 03:53

Using Visual Studio 2013 RC and C++, I\'m trying to pass an std::unique_ptr to a function that has been bound using std::bind. However, I\'m having

相关标签:
3条回答
  • 2020-12-21 04:14

    I had the same problem with VS 2012 recently. I believe this is a bug in MSVC; at least in MSVC++11 the pseudo-variadic expansion seems to forward the parameters by value to some internal function. Seems this hasn't been improved.
    As a workaround, I'm using lambdas instead, but another hack is required to make it work:

    std::function<void (std::unique_ptr<int>)> bound =
        [] (std::unique_ptr<int> arg) { func(std::move(arg)); };
    

    still doesn't compile. But if you add any captured value (even one that isn't used), it compiles:

    int x;
    std::function<void (std::unique_ptr<int>)> bound =
        [x] (std::unique_ptr<int> arg) { func(std::move(arg)); };
    
    0 讨论(0)
  • 2020-12-21 04:17

    You have to move the parameter into the bound call to func also. Not only in the invocation of bound

    bound(std::move(ptr));
    

    but also in the binding:

    std::function<void(std::unique_ptr<int>)> bound =
        std::bind(func,
                  std::bind(std::move<std::unique_ptr<int>&>,
                            std::placeholders::_1));
    

    This is compiling in VS2013 (update 4) for me.

    0 讨论(0)
  • 2020-12-21 04:22

    Functions bound with std::bind do not forward arguments, it copies them to the function. As a result, std::bind doesn't work with move-only types as of c++11. This problem is the idea behind proposals for "more perfect forwarding" (like this one). There's a newer one, but I can't seem to find it right now.

    0 讨论(0)
提交回复
热议问题