Boost logo

Boost Users :

Subject: [Boost-users] Passing reference params to boost::thread, parameter copies.
From: Jason Cipriani (jason.cipriani_at_[hidden])
Date: 2009-09-25 09:16:33


At the end of this message is a test program that uses boost::thread
to create two threads. The first is one that takes a parameter by
value, the second takes a parameter by reference. I have a couple of
questions about some behavior here:

1) When passing by value, why are so many copies of the data made? The
program output indicates that there are 9 (!) objects created (at most
5 exist simultaneously), when ideally there would be only 2 (the
original and the copy passed to the thread).

2) When passing by reference, why is the data being copied? The
copying behavior when passed by reference is identical to when the
param is passed by value (9 objects created, 5 simultaneously). Also,
and this isn't shown in the program below, but I would therefore
expect the program to crash if the boost::thread outlived the
referenced object (of course, it does not, since the object is
copied).

So, I'm surprised by the number of copies, this seems unreasonable,
and also I'm confused about why by value and by reference behave
identically.

Thanks,
Jason

=== BEGIN EXAMPLE ===

#include <boost/thread/thread.hpp>
#include <cstdio>

using namespace std;

class test {
public:
        test () { printf("%p\n", (void *)this); }
        test (const test &t) { printf("%p from %p\n", (void *)this, (void *)&t); }
        ~test () { printf("~%p\n", (void *)this); }
};

void expected_copy (test) {
        printf("in expected_copy\n");
}

void expected_nocopy (const test &) {
        printf("in expected_nocopy\n");
}

int main () {

        printf("expected_copy:\n");

        {
                test t;
                boost::thread thr(expected_copy, t);
                thr.join();
        }

        printf("expected_nocopy:\n");

        {
                test t;
                boost::thread thr(expected_nocopy, t);
                thr.join();
        }

        printf("complete\n");
        getchar();

}

=== END EXAMPLE ===


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net