Obviously the possible solution depends on the general architecture of your application (and run-time environment). In standard C++ an object life time defined with regard to the only execution thread and it's not a real time.
Hmm, i find this question very interesting, and as ArkM said, it's very run-time environment dependent...
I tried to implement a wrapper class that takes an dynamic allocated object and destroys it after X seconds. It uses the pthred library to create the timer in another thread
#include <iostream>
#include <cstdio>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
using namespace std;
class Exception {};
template < class T>
class ObjTimerWrapper
{
private:
T* obj_;
int seconds_;
pthread_mutex_t mutex;
pthread_t timer;
void DeleteObj()
{
pthread_mutex_lock( &mutex );
delete obj_;
obj_ = 0;
pthread_mutex_unlock( &mutex );
}
public:
ObjTimerWrapper( T* obj, unsigned int seconds):obj_(obj), seconds_(seconds)
{
pthread_mutex_init( &mutex, 0 );
pthread_create(&timer, NULL, ObjTimerWrapper::startTimer, (void*)this );
}
~ObjTimerWrapper()
{
pthread_join( timer, 0 );
pthread_mutex_destroy(&mutex);
cout<<"destructor called"<<endl;
}
void Lock() { pthread_mutex_lock( &mutex ); }
void UnLock() { pthread_mutex_unlock( &mutex ); }
T* operator->()
{
if ( ! obj_ ) throw Exception();
return obj_;
}
T* get()
{
if ( ! obj_ ) throw Exception();
return obj_;
}
static void* startTimer(void * arg);
};
template < class T>
void *ObjTimerWrapper<T>::startTimer(void* arg)
{
ObjTimerWrapper* p = (ObjTimerWrapper*)arg;
sleep( p->seconds_);
p->DeleteObj();
cout<<"timer expired, object destroyed-----------"<<endl;
return 0;
}
class X
{
public:
double x;
void iterate();
X( float xx ):x(xx){}
};
void X::iterate()
{
for( int i = 0; i < 7; ++i )
{
sleep(1);
}
cout<<"rdy"<<endl;
}
int main ( int argc, char* argv[] )
{
{
ObjTimerWrapper<X> myobj( new X(0), 1 );
myobj.Lock();
myobj->iterate();
myobj.UnLock();
}
cout<<"end program"<<endl;
}
ObjTimerWrapper contains the dynamically alocated object ( pointer to it is stored in T* obj_)
Well, what happenes is that the timer thread that runs
void *ObjTimerWrapper<T>::startTimer(void* arg)
issues sleeps for X secs and then destroys the contained object
The destructor of ObjTimerWrapper joines with the timer thread, so the object can not be destroyed before the seconds pass ( say if ObjTimerWrapper gets out of scope it will wait in it's destructor till the timer joins )
The real problem is sycronization.
What happens if you are currently working on the contained object and the timer thread tries to destroy it? the thing is i provided a mutex locking mechanism, so that the timer thread deletes the contained object only if the mutex is unlocked. But this leaves responsablility to the client code to lock and unlock the mutex each time you call a method on the contained object ( ie , in the example,
myobj.Lock();
myobj->iterate();
myobj.UnLock(); )