Reputation: 153
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;
}
Upvotes: 1
Views: 385
Reputation: 11002
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));
Upvotes: 3