On Sun, 26 Nov 2000, Baruch Even wrote:

> In insetgraphics draw() method I've now added the following construct in
> order to make sure that the x value is updated upon exit.
> 
> The construct:
> 
> | class set_var_on_exit {
> | public:
> |    set_var_on_exit(float & var, float new_val)
> |        : var_(var), new_val_(new_val)  {};
> |
> |    ~set_var_on_exit() { var_ = new_val_; };
> | private:
> |    float & var_;
> |    float new_val_;
> | };

This would be more useful as a template.

> and in the method I use:
> 
> | int lwidth = some_width_calculation_at_the_beginning;
> | set_var_on_exit set_x(x, x+lwidth);
> 
> I do this in order to guarantee that no matter what the exit point it will
> be, the x variable will be adjusted correctly, without any extra work,
> both for me now and for a future maintainer.

Any particular reason you can't just make the assignment in the first
place?  If you use the value of x throughout the function but know what
it's return value will be early on then you could instead use a temporary
variable to hold x's original value and assign the new value to x.
 
> In optimized code (-O2) it amounts to nothing more than the calculation at
> the start and assignment on exit. And for maintenance, this is most
> probably easier and less bug prone.

I agree it's a simple and neat trick but it's use is also very limited.

Allan. (ARRae)

Reply via email to