简体   繁体   中英

call_once to initialize a function

I am trying to initialize a function using 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. 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 .

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 . 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.

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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