user180574
user180574

Reputation: 6084

How to fix "use of deleted function" when using mutex and condition variable as member?

I am doing some multi-threading exercise and couldn't get this code pass compilation. I search online but so far not exactly sure about the cause.

#include <condition_variable>
#include <functional>
#include <iostream>
#include <mutex>
#include <thread>

using namespace std;

class FooBar {
  private:
    int n;

  public:
    FooBar(int n) {
        this->n = n;
    }

    void foo(function<void()> printFoo) {
        for (int i = 0; i < n; i++) {
            printFoo();
        }
    }

    std::mutex foo_mtx;
    std::condition_variable foo_cv;
};

void printFoo()
{
    cout << "foo";
}

int main ()
{
    FooBar foobar(10);
    std::thread foo_thread = std::thread(&FooBar::foo, foobar, printFoo);
    foo_thread.join();
    return 0;
}

This code compiles and runs well if I don't add mutex and condition variable.

error: use of deleted function ‘FooBar::FooBar(const FooBar&)’
error: use of deleted function ‘std::mutex::mutex(const std::mutex&)’
error: use of deleted function ‘std::condition_variable::condition_variable(const std::condition_variable&)’

Upvotes: 4

Views: 3640

Answers (1)

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275490

You are copying a fooBar. The compiler says you are not allowed to. You are not allowed to because a mutex cannot be copied.

std::thread foo_thread = std::thread(&FooBar::foo, std::ref(foobar), printFoo);

this will make that specific compiler error go away. Without building it I cannot be certain there aren't other problems.

std::thread foo_thread = std::thread([&foobar]{ foobar.foo(printFoo); });

this is a more sane way to solve the same problem. Lambdas are usually a better plan than using INVOKE based interfaces.

Upvotes: 5

Related Questions