c++ - call_once 初始化一个函数

标签 c++ multithreading lambda

我正在尝试使用 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/

相关文章:

c++ - 我正在尝试将灰度放入更大的黑色图像中。我收到此错误 OpenCV 错误 : Assertion failed

c++ - 如何在 Visual Studio 2017 中重新启用格式

c# - 如何使用 BlockingCollection<> 解决生产者/消费者竞争条件

java - 关于 Swing GUI 中的线程

java - 在 Java 中声明 lambda 数组

c# - Lambda 用法让我感到困惑

c++ - 在Qt中获取父类(super class)中子类的名称

c++ - 将 1 加到 N,在新行中打印每个总和(递归)

linux - 终止正在 Q​​Thread 中运行的正在进行的 QProcess?

c# - 如何有效地限制然后将结果与 linq/lambda 表达式连接?