BDE 4.14.0 Production release
Loading...
Searching...
No Matches
bslma_destructorguard

Macros

#define bslma_DestructorGuard   bslma::DestructorGuard
 This alias is defined for backward compatibility.
 

Detailed Description

Outline

Purpose

Provide a guard to unconditionally manage an object.

Classes

See also
bslma_destructorproctor, 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)
{
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). *
//***********************************************************
Definition bslma_destructorguard.h:132
Definition bsls_objectbuffer.h:276
TYPE & object()
Definition bsls_objectbuffer.h:351

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.

}

Macro Definition Documentation

◆ bslma_DestructorGuard

#define bslma_DestructorGuard   bslma::DestructorGuard