我正在尝试设计一个源自std :: thread的killable_thread类。
该类应该有一个名为die()的成员,可以调用该成员来终止该线程。
我的first attempt忽略了资源泄漏的问题。它只是尝试调用析构函数,但它不会编译:
/** 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
编译错误是:
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();
^~~~~~~~~~~~~~~~~~
我应该怎么做?
答案 0 :(得分:2)
~killable_thread();
编译器将其解释为将一元operator~
应用于使用默认构造函数killable_thread()
创建的临时对象。要像方法一样调用析构函数,你应该像下面这样调用它:
this->~killable_thread();
或
(*this).~killable_thread();
答案 1 :(得分:0)
您可能需要添加“this”关键字:
this->~killable_thread();
另一种方法是写:
delete this;
但是,如上所述,不建议在方法中调用析构函数