scoped()

Get to learn about the scoped function in this lesson.

Calling the destructor using scoped()

The program in the previous lesson has a weakness: The scopes may be exited before the destroy() function is executed, commonly by thrown exceptions. If the destroy() function must be executed even when exceptions are thrown, a solution is to take advantage of scope().

Instead of using the new keyword, another solution is to construct class objects by std.typecons.scoped. scoped() wraps the class object inside a struct, and the destructor of that struct object destroys the class object when it leaves the scope.

Get hands-on with 1200+ tech skills courses.