gpt4 book ai didi

c++ - 异步不会在 Visual Studio 2015 中调用移动构造函数

转载 作者:行者123 更新时间:2023-11-30 01:46:34 26 4
gpt4 key购买 nike

我在 Visual Studio 2015 Community 上编译包含以下内容的代码时遇到问题

auto f = async(launch::async,                  
&WorkerThread<Hash>::run,
WorkerThread<Hash>(mInputFile, mOutputFile),
i, numthreads, mBlockSize);
futures.push_back(std::move(f));

好吧,类似的问题已经在这里问过几十次了,但通常问题是缺席 std::move某处。

模板类 WorkerThread<Hash>不可复制(已删除复制构造函数和复制赋值运算符),但可移动。上面的代码产生 C2280: "WorkerThread<Hash>::WorkerThread(const WorkerThread<Hash> &)": attempted to reference deleted function (这是我的翻译)。

它似乎默认不生成移动构造函数,这对我来说没问题。当我明确地将它们设置为 default 时,我得到同样的错误,但现在它指的是 std::_Binder<std::_Unforced,_Ty,WorkerThread<Hash>,unsigned int,unsigned int,__int64>::_Binder(const std::_Binder<std::_Unforced,_Ty,WorkerThread<Hash>,unsigned int,unsigned int,__int64> &) .

非常欢迎任何想法。

更新:MCVE

如果您有上述编译器可用,请尝试编译并报告结果。我认为这可能是安装问题。

#include<future>
#include<memory>


class Foo {
public:
Foo() :mData(new int[100]) {}
void run() {}
private:
std::unique_ptr<int[]> mData;
};


int main()
{
auto f = std::async(std::launch::async, &Foo::run, Foo());
f.get();
}

最佳答案

编辑:该错误已在 MSVC 2015 Update 2 中修复。

这是一个 MSVC bug (帽子提示@bogdan 查找报告)。它的async (和 packaged_task ,似乎)实现将仿函数存储到 std::function 中,它不支持仅移动类型 - 因此不能用于符合标准的实现。

一个简单的解决方法是使用 shared_ptr相反:

auto f = async(launch::async,                  
&WorkerThread<Hash>::run,
std::make_shared<WorkerThread<Hash>>(mInputFile, mOutputFile),
i, numthreads, mBlockSize);
futures.push_back(std::move(f));

也可以考虑 Lambda(沿 [=]{WorkerThread<Hash>(mInputFile, mOutputFile).run(i, numthreads, mBlockSize); } 行),但这会导致行为发生变化:WorkerThread<Hash>不再在调用 async 的线程中构建, 但在线程中 async产卵。

关于c++ - 异步不会在 Visual Studio 2015 中调用移动构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32965663/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com