Attempting to reference a function to be deleted when using a mutex

I get a strange error working on a project. I created a super simple example to recreate the error.

I created a class. What I would like to do in this class is to have a getter function for my class that populates the values ​​of a struct. In the main application, the user will create an instance of this struct, pass it to the member function and be able to read the values ​​in structupon return. Due to the design of the actual class, this should happen in a separate thread. Here is what I have:

myClass.h:

#ifndef __MY_CLASS_H__
#define __MY_CLASS_H__

#include <mutex>

class myClass {
public:
    struct my_struct_s {
        int field1;
        short field2;
    };

    int get_data(my_struct_s & my_struct);

private:

};

#endif /* __MY_CLASS_H__ */

myClass.cpp:

#include "myClass.h"

int myClass::get_data(struct my_struct_s & my_struct)
{
    int var1 = 5;
    char var2 = 2;

    my_struct.field1 = var1;
    my_struct.field2 = var2;

    return 0;
}

main.cpp:

#include "myClass.h"
#include <iostream>
#include <thread>
#include <Windows.h>

bool thread_running;
std::thread thread;

void run_thread(myClass & lmyClass)
{
    myClass::my_struct_s my_struct;

    while (thread_running) {
        lmyClass.get_data(my_struct);

        std::cout << my_struct.field1 << std::endl;
        std::cout << my_struct.field2 << std::endl;

        Sleep(100);
    }
}

int main(int argc, char *argv[])
{
    myClass lmyClass; 

    thread_running = true;
    thread = std::thread(run_thread, lmyClass);

    Sleep(1000);
    thread_running = false;

    if (thread.joinable()) {
        thread.join();
    }

    getchar();

    return 0;
}

It works as expected. However, due to the asynchronous nature of the class, I need mutexes to protect data processed in different threads within the class.

std::mutext , , :

Error 1 error C2280: 'std::mutex::mutex(const std::mutex &)' : attempting to reference a deleted function ...

1) , .

2) ( ), , "getter" , -, , ? ?

+4
2

myclass, . , std::mutex, . , .

; , , , , .

+8

, .

myClass , :

mutex * mtx;

, :

mtx = new std::mutex();
-1

All Articles