本文介绍了与std :: unique的std :: async不编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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>'
}

为什么异步无法编译?我使用Microsoft Visual Studio 2012(v4.5.50709)。

Why 'async' doesn't compile? I use Microsoft Visual Studio 2012 (v4.5.50709).

推荐答案

这应符合标准,并且。

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

The reason it fails on VS is probably because std::async is allowed to store internal copies of its arguments, which will then get passed on to the called function at a later point.

在这种情况下,将需要在unique_ptr上执行两次:一个用于构造异步的中间对象,然后将参数传递给 foo 时进行第二个。两者之一可能会失败。但是,标准明确指出, async 的参数只能是MoveConstructible(第30.6.8.2节),而 unique_ptr

In this case, that would require two moves on the unique_ptr: One to construct the intermediate object for async and then a second one when passing the argument on to foo. One of the two probably fails. The Standard however explicitly states that the arguments to async must only be MoveConstructible (§ 30.6.8.2), which unique_ptr is.

所以我想说这是VS2012标准库实现中的错误。

So I would say this is a bug in VS2012's implementation of the standard library.

这篇关于与std :: unique的std :: async不编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 11:43