tr1::function - why so many temporaries?

N

n.torrey.pines

I believe boost::function is part of TR1, so imagine this is a job
interview question in 2009:

Guess how many times ~int_div() is called between "before" and "after"
and explain why. (I was surprised and still don't understand why) :


#include <iostream>
#include <boost/function.hpp>

typedef boost::function2<float, int, int> fun;

struct int_div {
float operator()(int x, int y) const { return ((float)x)/y; }
~int_div() { std::cout << "destructor\n"; }
};

int main() {
int_div i;
fun f;
{
std::cout << "before\n";
f = i;
std::cout << "after\n";
}
}
 
G

Greg Herlihy

I believe boost::function is part of TR1, so imagine this is a job
interview question in 2009:

Guess how many times ~int_div() is called between "before" and "after"
and explain why. (I was surprised and still don't understand why) :

#include <iostream>
#include <boost/function.hpp>

typedef boost::function2<float, int, int> fun;

struct int_div {
float operator()(int x, int y) const { return ((float)x)/y; }
~int_div() { std::cout << "destructor\n"; }

};

int main() {
int_div i;
fun f;
{
std::cout << "before\n";
f = i;
std::cout << "after\n";
}

}

Well, the answer is more times than std::tr1:function does:

#include <tr1/functional>
#include <iostream>

typedef std::tr1::function< float(int, int)> fun;

struct int_div
{
float operator()(int x, int y) const
{
return ((float)x)/y;
}
~int_div()
{
std::cout << "destructor\n";
}
};

int main()
{
int_div i;
fun f;

{
std::cout << "before\n";
f = i;
std::cout << "after\n";
}
}

Program Output:

before
destructor
destructor
after
destructor
destructor

Greg
 
P

Pete Becker

I believe boost::function is part of TR1, so imagine this is a job
interview question in 2009:

Guess how many times ~int_div() is called between "before" and "after"
and explain why. (I was surprised and still don't understand why) :

It depends on the implementation, and it's mostly unimportant. When I write

int i = 3;
cout << i << '\n';

how many times does the value of i get copied? Like ints, callable
objects should, in general, be small and easy to copy. If someone's
worried about how many times one gets copied they've probably got bigger
problems that they should be worrying about.

--

-- Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com)
Author of "The Standard C++ Library Extensions: a Tutorial and
Reference." (www.petebecker.com/tr1book)
 

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,764
Messages
2,569,564
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top