lhbortho lhbortho -4 years ago 278
C++ Question

Attempting to reference a deleted function, structure with mutex member

Here's my problem.

I have a structure like this.

struct threadInfo
{
std::condition_variable cv;
std::mutex m;
int priorityLevel;
};


When building my code I get this error


Error C2280
threadInfo::threadInfo(const threadInfo &)
: attempting
to reference a deleted function
PriorityListMutex



From my understanding it means that the constructor for
threadInfo
is called and it tries to copy the
mutex
which is not possible.

I don't have much experience with c++ and even though I somewhat understand what is happening, I'm not sure how to attempt to fix this. Any help would be great!

Here is the code that uses ThreadInfo

threadInfo info;
info.priorityLevel = priority;

priorityListMutex.lock();
for (std::list<threadInfo>::iterator it = threadList.begin(); it != threadList.end(); it++)
{
if ((*it).priorityLevel < info.priorityLevel)
{
threadList.insert(it, info);
break;
}
else if (it == threadList.end())
{
threadList.push_back(info);
break;
}
}
priorityListMutex.unlock();
std::unique_lock<std::mutex> lock(info.m);
info.cv.wait(lock);


I guess the structure is being copied somewhere in there, but I'm completely missing where.

Answer Source

You can solve your problem by avoiding copies and emplacing the structs directly in the list. This does require a custom constructor though. I've shortened your code sample to only show the emplacing portion:

#include <mutex>
#include <condition_variable>
#include <list>

struct threadInfo
{
    explicit threadInfo(int prio) : priorityLevel(prio) {}

    std::condition_variable cv;
    std::mutex m;
    int priorityLevel;
};

int main()
{
    std::list<threadInfo> threadList;

    int priorityLevel = 0;

    for (std::list<threadInfo>::iterator it = threadList.begin(); it != threadList.end(); it++) 
    {
        if ((*it).priorityLevel < priorityLevel)
        {
            threadList.emplace(it, priorityLevel); 
            break; 
        }
        else if (it == threadList.end())
        {
            threadList.emplace_back(priorityLevel);
            break;
        }
    }

    return 0;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download