Imagine you’re in a situation where you need to save and restore a value. For instance, let’s say you have a UMG widget that you want to hide temporarily, do some stuff, and then bring back its previous visibility state, all within a single function. The most straightforward approach might be to store the value in a temporary variable, modify it, and then revert it back, like this:

ESlateVisibility VisibilityState;

const ESlateVisibility PreviousVisibility = VisibilityState;
VisibilityState = ESlateVisibility::Hidden;

// Do smth. VisibilityState is Hidden here

// Restore the previous visibility state
VisibilityState = PreviousVisibility;

This method gets the job done, but it’s not very scalable. What if you need to manage multiple values? What if there are several exit points in your function? What if multiple functions require saving and restoring the same value? Duplicating this rather verbose code everywhere is not ideal. We can do it better.

We can use TGuardValue class from Unreal Engine which is a very simple RAII class that saves the value in its constructor and restores it in its destructor. Here’s how you can use it with the previous example:

ESlateVisibility VisibilityState;

{
    TGuardValue<ESlateVisibility> Guard(VisibilityState, ESlateVisibility::Hidden);
    // Do smth. VisibilityState is Hidden here
}
// Once we exit the scope, Guard will restore the previous value of VisibilityState