Quick Links:

bal | bbl | bdl | bsl

Namespaces

Component bslma_destructorguard
[Package bslma]

Provide a guard to unconditionally manage an object. More...

Namespaces

namespace  bslma

Detailed Description

Outline
Purpose:
Provide a guard to unconditionally manage an object.
Classes:
bslma::DestructorGuard guard to unconditionally manage an object
See also:
Component bslma_destructorproctor, Component bslma_autodestructor
Description:
This component provides a guard class template, bslma::DestructorGuard, to unconditionally manage an (otherwise-unmanaged) object of parameterized TYPE supplied at construction. The managed object is destroyed automatically when the guard object goes out of scope by calling the (managed) object's destructor.
Usage:
Suppose we have a situation where one of the two constructors will be called to create an object on the stack for performance reasons. The construction thus occurs within either of the branches of an if statement, so the object itself, to survive the end of the "then" or "else" block, must be constructed in a bsls::ObjectBuffer. Once constructed, the object would not be destroyed automatically, so to make sure it will be destroyed, we place it under the management of a bslma::DestructorGuard. After that, we know that however the routine exits -- either by a return or as a result of an exception being thrown -- the object will be destroyed.
  double usageExample(double startValue)
  {
      bsls::ObjectBuffer<std::vector<double> > buffer;
      std::vector<double>& myVec = buffer.object();

      if (startValue >= 0) {
          new (&myVec) std::vector<double>(100, startValue);
      }
      else {
          new (&myVec) std::vector<double>();
      }

      //***********************************************************
      // Note the use of the destructor guard on 'myVec' (below). *
      //***********************************************************

      bslma::DestructorGuard<std::vector<double> > guard(&myVec);
Note that regardless of how this routine terminates, myVec will be destroyed.
  // ...

  myVec.push_back(3.0);
Note that push_back could allocate memory and therefore may throw. However, if it does, myVec will be destroyed automatically along with guard.
  if (myVec[0] >= 5.0) {
      return 5.0;                                               // RETURN
Note that myVec is automatically destroyed as the function returns.
  }

  return myVec[myVec.size() / 2];
Note that myVec is destroyed after the temporary containing the return value is created.
  }