Gus
Gus

Reputation: 43

Threading in C++ : cannot convert argument 1 from 'const std::ofstream' to 'std::ofstream &'

I have a class that writes to a file on a thread

class A{
public:    
void writeToFile(ofstream& outFile, obj &a)
    {
        //...
    }
    thread memberThread1(ofstream& outFile, obj &a)
    {
        cout << "Thread 1 is now running " << endl;
        return thread ([=]{ writeToFile(outFile, a);});
    }
};

I got a few errors on the lambda function.

cannot convert argument 1 from 'const std::ofstream' to 'std::ofstream &'

note: Conversion loses qualifiers

I was able to fix the second argument a by doing a const_cast but I could not figure out how to fix the first argument.

Thanks!

Upvotes: 0

Views: 796

Answers (2)

M.M
M.M

Reputation: 141586

There's 2 issues here:

  • When capturing by value, captured objects default to const, although you can change this as shown in the top answer to that question.

  • Capturing by value copies the object, however ofstream is non-copyable. So even if you fix the first issue you will get a new error message about this second issue.

As noted by the other answer you can capture by reference instead. However you need to be careful to ensure that the original objects will not be destroyed before the thread finishes; and also that there are not race conditions (concurrent unprotected access) between the launched thread and other threads.

Upvotes: 2

Christophe
Christophe

Reputation: 73376

The problem is that your lambda capture is by value, which is not possible for outFile. Try capturing by reference:

   return thread ([&]{ writeToFile(outFile, a);});

Upvotes: 4

Related Questions