bind (excessive?) argument copying
I was recently surprised to find that boost::bind seems to copy
arguments a number of times when called. For example, this program:
class C
{
public:
C() {}
C(const C &c) : data(c.data) { std::cout << "C(const C &c)\n"; }
boost::array
Hi Trent, <snipped code>
Four copies - I had hoped to only see a single copy. Logically, there doesn't seem to be a need for more than one copy. Is there an implementation issue that requires this many copies?
Short answer, no. It could be less.
I was hoping to use bind with some moderately weighted objects, however the number of copies that seem to occur may be prohibitive for me. (I realise that dynamically allocating objects and passing around pointers is an alternative but I'd rather avoid that if possible.)
Will boost::bind( foo, boost::ref(c)); cook your goose? Regards, Matt. matthurd@acm.org
On Wed, 05 Jan 2005 14:11:19 +1100, Trent Hill
I was recently surprised to find that boost::bind seems to copy arguments a number of times when called. For example, this program:
Use boost::ref or boost::cref. From the docs (http://boost.org/libs/bind/bind.html): ---8<--- a copy of the value of i is stored into the function object. boost::ref and boost::cref can be used to make the function object store a reference to an object, rather than a copy: int i = 5; bind(f, ref(i), _1); ---8<--- -- Caleb Epstein caleb dot epstein at gmail dot com
Trent Hill wrote: [...]
int main(int a_argc, char **a_argv) { C c; boost::bind(&foo, c); return EXIT_SUCCESS; }
results in this output (Visual C++ .NET with /O2):
C(const C &c) C(const C &c) C(const C &c) C(const C &c)
Four copies - I had hoped to only see a single copy. Logically, there doesn't seem to be a need for more than one copy. Is there an implementation issue that requires this many copies?
Not really, but eliminating the unnecessary copies is (relatively) hard, at least with the current code base (it has been developed with portability in mind and supports VC6, among others). The specification requires one copy. One more is almost unavoidable. The other two can be eliminated, in theory. But...
I was hoping to use bind with some moderately weighted objects, however the number of copies that seem to occur may be prohibitive for me.
... please note that the copies occur at bind time. In a typical scenario you bind once and call O(N) times (or bind and store in a function<> with the associated dynamic memory allocation), so this isn't usually a problem. And, as others have pointed out, there's always ref(). ;-)
participants (4)
-
Caleb Epstein
-
Matt Hurd
-
Peter Dimov
-
Trent Hill