C++ call deconstructor explicitly
//Util.h #ifndef Util_H #define Util_H #include <chrono> #include <ctime> #include <fstream> #include <functional> #include <iostream> #include <thread> #include <unistd.h> #include <uuid/uuid.h> using namespace std; class Util { public: Util(); ~Util(); static char *uuidValue; static char *dtValue; static int InitNum; char *getTimeNow(); char *getUuid(); void swap(int *left, int *right); void threadLE(int x,int y,int z,string str); void threadLE2(int x,int y,int z,string str); }; #endif
//Util.cpp #include "Model/Util.h" char *Util::uuidValue = (char *)malloc(40); char *Util::dtValue = (char *)malloc(20); int Util::InitNum = 0; Util::Util() { cout << "Constructor num=" << ++InitNum << endl; } Util::~Util() { cout << "Deconstructor and num=" << InitNum << endl; if (NULL != Util::dtValue) { free(Util::dtValue); Util::dtValue = NULL; } if (NULL != Util::uuidValue) { free(Util::uuidValue); Util::uuidValue = NULL; } } char *Util::getTimeNow() { time_t rawTime = time(NULL); struct tm tmInfo = *localtime(&rawTime); strftime(dtValue, 20, "%Y%m%d%H%M%S", &tmInfo); return dtValue; } char *Util::getUuid() { uuid_t newUUID; uuid_generate(newUUID); uuid_unparse(newUUID, uuidValue); return uuidValue; } void Util::threadLE(int x, int y, int z, string str) { thread t1([](int xx, int yy, int zz, string sstr) { Util ul; for(int i=0;i<xx;i++) { cout<<"Num="<<i<<",uuid="<<ul.getUuid()<<endl; } for(int i=0;i<yy;i++) { cout<<"Uuid="<<ul.getUuid()<<",Num="<<i<<endl; } for(int i=0;i<zz;i++) { cout<<"Num="<<i<<endl; } cout<<"The string is "<<endl<<sstr<<endl; }, x, y, z, str); t1.join(); cout << getTimeNow() << ",finished in threadLE!" << endl; } void Util::threadLE2(int x, int y, int z, string str) { thread t1([](int xx, int yy, int zz, string sstr) { Util ul; for(int i=0;i<xx;i++) { cout<<"Num="<<i<<",Uuid="<<ul.getUuid()<<endl; } for(int i=0;i<yy;i++) { cout<<"Uuid="<<ul.getUuid()<<",Num="<<i<<endl; } for(int i=0;i<zz;i++) { cout<<"Num="<<i<<endl; } cout<<"The string is "<<endl<<sstr<<endl; ul.~Util(); },x, y, z, str); t1.join(); cout << getTimeNow() << ",finished in void Util::threadLE2(int x,int y,int z,string str)!!" << endl; }
//main.cpp #include "Model/Util.h" void threadLE1(int x, int y, int z, string str); void threadLE2(int x,int y,int z,string str); int main(int agrs, char **argv) { try { threadLE2(atoi(argv[1]),atoi(argv[2]),atoi(argv[3]),argv[4]); } catch(const std::exception& e) { std::cerr << e.what() << '\n'; } } void threadLE2(int x,int y,int z,string str) { Util ul; ul.threadLE2(x,y,z,str); } void threadLE1(int x, int y, int z, string str) { Util ul; ul.threadLE(x,y,z,str); }
To invoke the deconstructor explicitly,you just need obj.~Deconstructor() as below in line 90
ul.~Util();
The executed result as below.