check if a boost point_xy is initialized or not?

770 Views Asked by At

I defined a typedef and:

typedef boost::geometry::model::d2::point_xy<double> boost2dPoint;
boost2dPoint min_p;
//.
//.(under a condition: min_p will be initialized)
//.
for(Region::Iterator itv = s.beginVer(); itv != s.endVer(); ++itv )
{
  Region::Point v_point = (*itv).pnt();
  if( (v_point(0) == min_p.x()) && (v_point(1) == min_p.y()) )
  {
     return *itv;
  }
}

I received a warning

‘min_p’ may be used uninitialized in this function [-Wmaybe-uninitialized]

how can I check if min_p is initialized or not??

3

There are 3 best solutions below

4
On

You cannot, at least not with that object alone. Uninitialized data is not specially marked, it just doesn't have a specified value. You could have a bool flag that's initially set to false and set it to true when min_p is initialized, although if you're going that route, I'd suggest using boost::optional:

// this is default-initialized to know that its
// data part (a boost2dpoint) is uninitialized
boost::optional<boost2dpoint> min_p; 

// initialize later
if(some_condition()) {
  min_p = boost2dpoint(foo, bar);
}

// use still later:

// Check if min_p has associated data. 
if(min_p) {
  for(Region::Iterator itv = s.beginVer(); itv != s.endVer(); ++itv )
  {
    Region::Point v_point = (*itv).pnt();

                          // +-- note: -> instead of . here. boost::optional is
                          // v                  designed to look like a pointer.        
    if( (v_point(0) == min_p->x()) && (v_point(1) == min_p->y()) )
    {
      return *itv;
    }
  }
}

I'll leave a link to the documentation, which is not terribly long.

1
On

You will get this warning if you try to use a variable that has any chance of being uninitialized. You need to provide an initialization for each path. Either provide a default initialization when you declare the variable, or provide a value in the else case of your condition.

3
On

It's not a runtime condition.

I't s static analysis (compiletime) daignostic.

Just initialize your data.

boost2dPoint min_p {};

or

boost2dPoint min_p (0,0);