可杀死线程类中的编译错误 [英] compilation error in killable thread class

查看:81
本文介绍了可杀死线程类中的编译错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试设计一个从std :: thread派生的killable_thread类.

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

该类应具有一个名为die()的成员,可以调用该成员杀死线程.

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();
       ^~~~~~~~~~~~~~~~~~

我应该怎么做?

推荐答案

~killable_thread();

编译器将其解释为将一元operator~应用于使用默认构造函数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();

(*this).~killable_thread();

这篇关于可杀死线程类中的编译错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆