我正在尝试使用 call_once(...) 初始化一个函数。我的程序给我编译错误“std::once_flag::once_flag(const std::once_flag&)”:试图引用已删除的函数。我不明白为什么删除该功能。
#include "stdafx.h"
#include <string>
#include <thread>
#include <future>
#include <cstdio>
#include <iostream>
#include <queue>
#include <condition_variable>
using namespace std;
once_flag flagZero;
string printerFunc(queue<char>& input, once_flag& flag){
string output = "";
function<void(string&)> f;
call_once(flag, [&](){
f = [&](string& output){}; });
f(output);
return output;
}
int _tmain(int argc, _TCHAR* argv[])
{
string input = "0102030";
queue<char> inputQueue;
for(char c : input){
inputQueue.push(c);
}
auto zeros = async(printerFunc, ref(inputQueue), flagZero);
this_thread::sleep_for(chrono::seconds(10));
return 0;
}
最佳答案
My program is giving me the compiling error
std::once_flag::once_flag(const std::once_flag&)
: attempting to reference a deleted function.
这是一个复制构造函数:
std::once_flag::once_flag(const std::once_flag&)
根据 the documentation : std::once_flag
既不可复制也不可移动。这是通过确保删除相关的构造函数和赋值运算符函数来强制执行的。
与 std::thread
一样参数按值传递。
通过引用传递它们并确保 flagZero
不被复制将其包装在 std::ref
中并按如下方式传递:std::async (printerFunc, ref(inputQueue),
std::ref
(flagZero));
关于c++ - call_once 初始化一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46963551/