与std :: unique的std :: async无法编译

时间:2013-06-06 06:32:41

标签: c++ c++11

#include <iostream>
#include <memory>
#include <future>

using namespace std;

unique_ptr<int> uq(new int);

void foo(unique_ptr<int> q)
{}

int main()
{
    foo(move(uq));
    // ^ OK

    async(foo, move(uq));
    // ^ Error: error C2248: 'std::unique_ptr<_Ty>::unique_ptr' :
    //    cannot access private member declared in class 'std::unique_ptr<_Ty>'
}

为什么'async'不能编译?我使用Microsoft Visual Studio 2012(v4.5.50709)。

1 个答案:

答案 0 :(得分:2)

这应该符合标准,does work on gcc

它在VS上失败的原因可能是因为允许std::async存储其参数的内部副本,然后这些副本将在稍后传递给被调用的函数。

在这种情况下,需要在unique_ptr上移动两个:一个用于构造异步的中间对象,然后在将参数传递给foo时再构建第二个。其中一个可能失败了。然而,标准明确指出async的参数必须只是MoveConstructible(第30.6.8.2节),unique_ptr是。

所以我想说这是VS2012实施标准库的一个错误。