【发布时间】:2013-10-18 23:30:53
【问题描述】:
使用 Visual Studio 2013 RC 和 C++,我尝试将 std::unique_ptr 传递给已使用 std::bind 绑定的函数。但是,我遇到了麻烦,因为当我尝试这个时,VS 似乎不喜欢它。这是我要编译的内容:
#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;
}
这在 GCC 4.8.1 中编译,但在 VS2013 RC 中不编译。我一直在 VS 中遇到移动语义问题,但我真的很想使用 std::unique_ptr 而不是 std::shared_ptr 或原始指针。
我发现的一个解决方法是更改函数签名以接受 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 签名的情况下解决这个问题?
谢谢!
【问题讨论】:
-
你不能按值传递 unique_ptr,它没有复制构造函数。
-
因此
std::move()。如果我直接调用func(std::move(ptr)),调用它会非常好,但在绑定时就不行。 -
那为什么不将
func改为接受unique_ptr<T>&& -
因为它不能在 VS2013 中编译...在这种情况下,将参数设置为
std::unique_ptr<T>与std::unique_ptr<T>&&没有任何实际区别。
标签: c++ visual-studio c++11 visual-studio-2013