SSteven
SSteven

Reputation: 753

compilation error in killable thread class

I am trying to design a killable_thread class which derives from std::thread.

The class should have a member named die(), which can be invoked to kill the thread.

My first attempt ignores the problem of leaking resources. It simply tries to invoke the destructor, but it doesn't compile:

/** killable_thread

    A class that inherits the thread class to provide a kill() operation.
    version 1.0 : only kills the thread. Ignores resources.

**/

#ifndef KILLABLE_THREAD
#define KILLABLE_THREAD

#include <thread>       /// thread
#include <iostream>     /// cout, endl


struct killable_thread : std::thread
{
   /// inherit the thread class' constructor
   /// [CPL], $20.3.5.1
   using std::thread::thread;
   using std::thread::operator=;

   ~killable_thread()
   {
   }

   void die()
   {
      ~killable_thread();
   }
};


void f();


int main()
{
   killable_thread kt {f};

   kt.die();

   std::cout << "OK" << std::endl;
}


void f()
{
}

#endif  ///  KILLABLE_THREAD


The compilation error is:

main.cpp: In member function 'void killable_thread::die()':
main.cpp:28:7: error: no match for 'operator~' (operand type is 'killable_thread')

       ~killable_thread();
       ^~~~~~~~~~~~~~~~~~

How should I go about it?

Upvotes: 0

Views: 133

Answers (2)

3CxEZiVlQ
3CxEZiVlQ

Reputation: 38425

~killable_thread();

Compiler interprets it like apply the unary operator~ to a temporary object created with the default constructor killable_thread(). To call the destructor like a method you should invoke it like bellow:

this->~killable_thread();

or

(*this).~killable_thread();

Upvotes: 2

gchen
gchen

Reputation: 1173

You may need to add the “this” keyword:

this->~killable_thread();

Another way is to write:

delete this;

However, as mentioned above, calling the destructor in a method is not recommended

Upvotes: 0

Related Questions