Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

Tip of the Day
Language: C++
Expertise: Intermediate
Oct 26, 1999



Application Security Testing: An Integral Part of DevOps

Killing an Object Prematurely

Sometimes, you need to force an object to destroy itself because its destructor performs an operation needed immediately. For example, when you want to release a mutex or close a file:
  void func(Modem& modem)
      Mutex mtx(modem); // lock modem
      /* at this point, you want to release the 
modem lock by invoking Mutex's dtor */ do_other_stuff(); //modem is still locked } //Mutex dtor called here
After the function Dial() has finished, the modem no longer needs to be locked. However, the Mutex object will release it only when func() exits, and in the meantime, other users will not be able to use the modem. Before you suggest to invoke the destructor explicitly, remember that the destructor will be called once again when func() exits, with undefined behavior:
void func(Modem& modem)
    Mutex mtx(modem); // lock modem
    mtx->~Mutex(); // very bad idea!
} //Mutex dtor called here for the second time
There is a simple and safe solution to this. You wrap the critical code in braces:
void func(Modem& modem)
      Mutex mtx(modem); // lock modem
    } //mtx destroyed here
     //modem is not locked anymore
Danny Kalev
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date