Visual Studio 2013 C ++ - passing std :: unique_ptr to a related function

Using Visual Studio 2013 RC and C ++, I am trying to pass a std::unique_ptrfunction that was bound using std::bind. However, I'm having problems because VS doesn't seem to like it when I try to do this. Here is what I am trying to compile:

#include <memory>
#include <iostream>
#include <functional>

void func(std::unique_ptr<int> arg)
{
    std::cout << *arg << std::endl;
}

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

    std::unique_ptr<int> ptr(new int(42));
    bound(std::move(ptr));

    return 0;
}

This compiles in GCC 4.8.1, but not in VS2013 RC. I always had problems with move semantics in VS, but I'd really like to use pointers std::unique_ptrinstead of std::shared_ptror raw.

, , - , std::unique_ptr&, VS GCC, func std::unique_ptr, , - :

#include <memory>
#include <iostream>
#include <functional>
#include <future>
#include <string>

void func(std::unique_ptr<int>& arg)
{
    std::cout << *arg << std::endl;
}

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

    std::unique_ptr<int> ptr(new int(42));
    std::promise<void> prom;
    std::async(
        [&bound, &ptr, &prom]
        {
            std::unique_ptr<int> movedPtr = std::move(ptr);
            prom.set_value();

            bound(std::move(movedPtr));
        });

    prom.get_future().wait();

    // Wait here
    std::string dummy;
    std::cin >> dummy;
}

func?

!

+4
3

VS 2012 . , MSVC; , MSV++ 11 - , -, . , . lambdas , :

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

. ( , ), :

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

func. bound

bound(std::move(ptr));

:

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

VS2013 ( 4) .

+1

The functions associated with std::binddo not forward the arguments; they copy them to the function. As a result, it std::binddoesn’t work with move types only with C ++ 11. This problem is the idea of ​​suggestions for a "more advanced forwarding" ( like this one ). There is a newer one, but I can’t find it right now.

0
source

All Articles