Functors with behaviour in the destructor

P

Paul MG

Hi

A brief question:

Is it generally considered idiomatic/good C++ to have behaviour in the
destructor of a function object?

For instance, consider a function object whose constructor takes
references to variables in the calling scope. During the use of the
functor, ie in a call to an STL algorithm, the functor stores away
data in its member variables. Then just before the algorithm returns,
as the functor goes out of scope, its destructor does some work with
the member variables, setting the results back into the variables it
still has references to.

I hope this makes sense. If it is any use, I am seeing this pattern at
http://www.gotw.ca/gotw/041.htm. I just found it rather surprising,
though once I had read it I sort of saw the elegance of it.

Is this a standard thing to do?

thanx for input,

pmg:)
 
C

Cy Edmunds

Paul MG said:
Hi

A brief question:

Is it generally considered idiomatic/good C++ to have behaviour in the
destructor of a function object?

For instance, consider a function object whose constructor takes
references to variables in the calling scope. During the use of the
functor, ie in a call to an STL algorithm, the functor stores away
data in its member variables. Then just before the algorithm returns,
as the functor goes out of scope, its destructor does some work with
the member variables, setting the results back into the variables it
still has references to.

I hope this makes sense. If it is any use, I am seeing this pattern at
http://www.gotw.ca/gotw/041.htm. I just found it rather surprising,
though once I had read it I sort of saw the elegance of it.

Is this a standard thing to do?

thanx for input,

pmg:)

As Edward Asner once said on the Mary Tyler Moore show: "It's cute. I hate
cute."

Doing real work as a side effect of a destructor is OK for a puzzle but I
would prefer a less whimsical design for industrial strength code.
 
D

Dhruv

There's a post somewhere around here that says:
std::for_each makes 3 copies of the function object passed to it. Is that
enough to convince you not to use such a tactic, unless of course, you
have a reference counted function object. But, then again, it will give
problems. If the objects upon which the algotihm works itself calls some
other function, to which the obeject is passed, and you expect the
destructor to be called for those individual data sets, then, you cannot
do it. It (the dtor) will be called when the last function that used the
object has exited.

-Dhruv.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,734
Messages
2,569,441
Members
44,832
Latest member
GlennSmall

Latest Threads

Top