Boost logo

Boost Users :

Subject: Re: [Boost-users] What's wrong with my code?
From: Lee Clagett (forum_at_[hidden])
Date: 2014-05-04 09:47:10


On Sun, May 4, 2014 at 5:08 AM, Bill David <billdavidcn_at_[hidden]> wrote:

> Hi all,
>
> I meet a problem with some code with boost and want to ask for some help
> here.
>
> To the following code:
>
> #include <list>
>
> using namespace std;
>
>
>
> #include "boost/function.hpp"
>
> #include "boost/foreach.hpp"
>
> #include "boost/bind.hpp"
>
> using namespace boost;
>
>
>
> void InsertItemHelper(list<int>& inContainer, list<int>::iterator&
> ioPosition, const list<int>::value_type& inItem)
>
> {
>
> ioPosition = inContainer.insert(ioPosition, inItem);
>
> }
>
>
>
> void WorkerFunction(const list<int>& inContainer, boost::function<void(int)>
> const& inAddItemCallback)
>
> {
>
> BOOST_FOREACH(auto item, inContainer)
>
> {
>
> inAddItemCallback(item);
>
> }
>
> }
>
>
>
> void Print(const list<int>& inContainer)
>
> {
>
> BOOST_FOREACH(auto item, inContainer)
>
> {
>
> std::cout << item << endl;
>
> }
>
> }
>
>
>
> int main()
>
> {
>
> list<int> sourceContainer;
>
> sourceContainer.push_back(1);
>
> sourceContainer.push_back(2);
>
> sourceContainer.push_back(3);
>
>
>
> list<int> targetContainer;
>
> list<int>::iterator pos = targetContainer.end();
>
>
>
> boost::function<void(int)> addItemCallbackFxn(boost::bind(&
> InsertItemHelper, targetContainer, pos, _1));
>
> WorkerFunction(sourceContainer, addItemCallbackFxn);
>
>
>
> return 0;
>
> }
>
> When I run it on Windows with VS2012, I always get a “list insert iterator
> outside range” error with:
>
> inContainer.insert(ioPosition, inItem);
>
> It seems targetContainer I passed to boost::bind is copied so that the
> following debug error of STL is hit:
>
> #if _HAS_ITERATOR_DEBUGGING
> if (_Where._Mycont != this)
> _DEBUG_ERROR("list insert iterator outside range");
> #endif /* _HAS_ITERATOR_DEBUGGING */
>
> But I am passing targetContainer as a reference and after the error, I
> can correctly get data in it.
>
>
>
> Does anybody know what’s wrong behind?
>
>
>
> Thanks,
>
> BD
>
>
boost::bind copies the arguments into a functor that it returns. boost::ref
(mutable reference) or boost::cref (const reference) can be used to change
this behavior.

addItemCallbackFxn(boost::bind(InsertItemHelper,
boost::ref(targetContainer), boost::ref(pos), _1));

Lee



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