Why Use RWTRefHolder<T>
All parameters passed to the rwtMakeScopeGuard() family of functions are held by value within the scope guard. These values are later passed as parameters to the named function when the guard destructor is invoked. Note that since the parameters are held by value, changes to values of objects that have been copied into the scope guard will not be visible when the guard function is invoked. Example:
// ...
void print_string(const RWCString& s) {
printf ("%s\n", s.data());
}
// ...
RWCString s;
s = "hello world!";
RWScopeGuard sg = rwtMakeScopeGuard(print_string, s);
s = "goodbye!";
// ...
The above code generates the following output:
hello world!
The initial value is displayed because the scope guard holds a copy of the
RWCString 's' as it was at the time the scope guard was created. If you want the scope guard to see updates to a parameter that is passed after the construction of the guard, you must pass a pointer to that object, or use
RWTRefHolder<T> to hold a reference by value.
Example:
// ...
RWCString s;
s = "hello world!";
RWScopeGuard sg = rwtMakeScopeGuard(print_string, rwtMakeRef(s));
s = "goodbye!";
// ...
This code generates the following output:
goodbye!