Skip to content
Advertisement

C++ std::thread “Attempt to use a deleted function”

Here’s the relevant code and the relevant error, I’m not really sure what to make of it.

Breaker::Thread::Thread(std::string name, std::string desc, void* func)
{
    std::thread _thread(func);

    _thread.join();
}

That’s in thread.cpp, the next is in log.cpp…

thread = new Breaker::Thread("System Log", loop);

and

void* Breaker::Log::loop()
{
    add("test");
}

Here’s the relevant error:

In file included from /home/nope/Documents/dev/C++/Breaker Engine/src/core/thread.cpp:25:
In file included from /home/nope/Documents/dev/C++/Breaker Engine/src/core/thread.h:28:
/usr/bin/../include/c++/v1/thread:332:5: error: attempt to use a deleted function
    __invoke(_VSTD::move(_VSTD::get<0>(__t)), _VSTD::move(_VSTD::get<_Indices>(__t))...);
    ^
/usr/bin/../include/c++/v1/thread:342:5: note: in instantiation of function template specialization 'std::__1::__thread_execute<void *>' requested here
    __thread_execute(*__p, _Index());
    ^
/usr/bin/../include/c++/v1/thread:354:42: note: in instantiation of function template specialization 'std::__1::__thread_proxy<std::__1::tuple<void *> >'
      requested here
    int __ec = pthread_create(&__t_, 0, &__thread_proxy<_Gp>, __p.get());
                                         ^
/home/nope/Documents/dev/C++/Breaker Engine/src/core/thread.cpp:95:14: note: in instantiation of function template specialization
      'std::__1::thread::thread<void *&, void>' requested here
        std::thread _thread(func);
                    ^
/usr/bin/../include/c++/v1/type_traits:1027:5: note: '~__nat' has been explicitly marked deleted here
    ~__nat() = delete;
    ^

Advertisement

Answer

I think the problem is the declaration of the parameter func. It is declared as a void pointer instead of a pointer to a function returning void.

Instead of,

Breaker::Thread::Thread(std::string name, std::string desc, void* func)

I think you mean,

Breaker::Thread::Thread(std::string name, std::string desc, void (*func) ())

Note, loop must be a static member for this to work.

Additionally, you might want to consider using std::function. It’s a much more modern and cleaner interface than using void pointers.

Breaker::Thread::Thread(std::string name, std::string desc, std::function<void()> func)
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement