简体   繁体   English

call_once初始化一个函数

[英]call_once to initialize a function

I am trying to initialize a function using call_once(...). 我正在尝试使用call_once(...)初始化函数。 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&)':尝试引用已删除的函数。 I don't understand why the function is deleted. 我不明白为什么删除这个功能。

#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&) :尝试引用已删除的函数

This is a copy constructor : 这是一个复制构造函数

std::once_flag::once_flag(const std::once_flag&)

As per the documentation : std::once_flag is neither copyable nor movable . 根据文档std::once_flag 既不可复制也不可移动 This is enforced by ensuring that the relevant constructors and assignment operator functions are deleted. 通过确保删除相关构造函数和赋值运算符函数来强制执行此操作。


Just as with std::thread the arguments are passed by value. 就像std::thread ,参数是按值传递的。

To pass them by reference and to ensure that flagZero is not copied wrap it in std::ref and pass it as follows: std::async(printerFunc, ref(inputQueue), std::ref (flagZero)); 要通过引用传递它们并确保不复制flagZeroflagZero其包装在std::ref并按如下方式传递: std::async(printerFunc, ref(inputQueue), std::ref (flagZero));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM