开发者

Copy constructor not called when using boost::bind, boost::shared_ptr, and boost::thread together

I am creating a new boost::thread using boost::bind, and storing it in a boost::shared_ptr.

I am passing a function and argument to the boost::thread, but when the thread is started, it does not correctly call the copy constructor for the function argument.

The thread creation method I'm using is a very common Boost pattern, so I don't think that's where the problem is:

void myclass::myfunc() {
   Workflow wfOriginal;
   boost::shared_ptr<boost::thread>(
       new boost::thread(boost::bind(&myclass::anotherfunc, this, wfOriginal)));
}
// ...
void myclass::anotherfunc(Workflow wfCopied) {
   // Doing something
}

I am trying to copy the Workflow from myfunc() to anotherfunc().

Workflow contains a collection, so I have provided a copy constructor that copies the elements inside the existing collection to the new Workflow.

Unfortunately, when anotherfunc() is called by the new thread, the collection inside wfCopied is empty!

I can tell that the Workflow object was partially copied, because other members like strings and ints have been copied, but the elements in the collection have not.

I have verified that the copy constructor works correctly by testing it with this code:

Workflow wf;
// ... insert some elements into wf...
Workflow wf1 = wf;
// wf1 has the same elements

I want to emphasize that my tests showed me that W开发者_如何学编程orkflow's copy constructor works fine.

But for completeness, here is the copy constructor for Workflow:

Workflow::Workflow(const Workflow& workflow) {
    this->_id = workflow._id;
    (this->_tasks).clear();
    Workflow::TaskCollectionConstIterator it;
    for (it = (this->_tasks).begin(); it < (this->_tasks).end(); it++)
        (this->_tasks).push_back(*it);
}

Can anyone help me?


It seems your copy constructor is flawed. You're copying from your empty vector to your vector. Which results in nothing being copied.

I think you mean:

for (it = (workflow->_tasks).begin(); it < (workflow->_tasks).end(); it++)
    (this->_tasks).push_back(*it);


Do you know what constructor initialization list is? And why exactly do you clear container in constructor?

Workflow::Workflow(const Workflow& workflow): _id(workflow._id),
    _tasks(workflow._tasks.begin(), workflow._tasks.end()) 
{}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜