[osg-users] std::vector instances from osg::geode derived class error

Jean-Sébastien Guay jean-sebastien.guay at cm-labs.com
Fri Nov 13 12:12:27 PST 2009


Hi Thorsten,

> osg::ref_ptr<TGBaseWidget> WidgNode01 = new TGBaseWidget(2,1);

This is pretty basic... Look at this:

       for(i=count_width; i>0; i--)
       {
(1)     ElementLower.push_back(
           new TGWidgetElement(posX, posY, "WidgElementSideLower.png"));
         posX += 15;
         posY += 15;
(2)     int elementnumber = i - 1;
         std::cout << elementnumber << std::endl;
(3)     ElementLower[elementnumber].get()->setDataVariance(
           osg::Object::DYNAMIC);
         this->addChild(ElementLower[elementnumber].get());
       }

Now, trace this in your head. When count_width is 2 (which is the case 
when you call the constructor as you did above), i starts at 2. Then, 
you push_back one TGWidgetElement into ElementLower at (1), so 
ElementLower contains 1 element at index 0. Then you calculate 
elementnumber as i-1 = 2-1 = 1 at (2), and then you try to access 
ElementLower[elementnumber] which is ElementLower[1]. That doesn't exist 
(because ElementLower contains one element at index 0, nothing at index 
1. Thus you get a crash, because you tried to access a vector with an 
index out of its bounds.

There are a few ways to fix this, but I'll let you find them yourself. 
It's a very basic bug which you could have found for yourself by running 
your code in a debugger, setting a breakpoint at the start of the for 
loop, and then running one line at a time to check the values as you go.

Hope this helps,

J-S
-- 
______________________________________________________
Jean-Sebastien Guay    jean-sebastien.guay at cm-labs.com
                                http://www.cm-labs.com/
                         http://whitestar02.webhop.org/


More information about the osg-users mailing list