开发者

I have to call Destructor explicitly

开发者 https://www.devze.com 2023-02-28 18:59 出处:网络
class TsDatabasePool { private: TsDatabasePool开发者_开发技巧(int numDBConn, std::string& DBName, std::string& DBType);
class TsDatabasePool
{
private:
    TsDatabasePool开发者_开发技巧(int numDBConn, std::string& DBName, std::string& DBType);
            static  TsDatabasePool* objInst_;             
public:
           ~TsDatabasePool();               
    QSqlDatabase* borrowFromPool();      
    void returnToPool(QSqlDatabase*);
static bool createInstance(std::string& DBName, std::string& DBType);
static TsDatabasePool* getInstance();

};

My destructor is not called implicitly. Object instance used objInst_ is allocated in private constructor. I dont want to call destructor or call delete objInst_ inside any existing function. Can anyone tell me what should i do


I believe what you are trying to do here is destroy a singleton object.
It can be done as follows in a Singlethreaded Enviornment:

void TsDatabasePool::Destroy()  
{   
    if (objInst_) 
    {        
        delete objInst_;       
        objInst_= 0x0;   
    } 
} 

Ideally, You can use something like shared_ptr to ensure that the object stays around until no-one needs it any more.


You can use std::auto_ptr<TsDatabasePool> template instead of raw pointer. std::auto_ptr template will call operator delete on your pointer automatically at application exit.


Until you deallocate objInst_, you can not call the destructor for that variable. You need to delete it for sure.


The correct way to free memory and call the destructor for objInst_ is to call

delete objInst_;

Unfortunately, you cannot (should not) call the destructor unless you also delete it. This is part of the design of the C++ language.

Since objInst_ is static you will need to add a "static void shutdown()" method and call it at some point in your code or register it with atexit function.

Edit: realized objInst_ is static.

0

精彩评论

暂无评论...
验证码 换一张
取 消