"strict aliasing" problem in gcc 4.1.2

Have simple program
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <iostream>
#include <list>

class CBase 
{
  int m_Base;
public:
  CBase() {}
  CBase(int Ai) {m_Base = Ai;}
  virtual ~CBase() {}
  virtual void Print() { std::cout << "  " << m_Base << std::endl;}
};

class CDerived : public CBase
{
  double m_Derived;
public:
  CDerived() {}
  CDerived(double Ai) {m_Derived = Ai;}
  ~CDerived() {}
  virtual void Print() { std::cout << "  " << m_Derived << std::endl;}
};

typedef std::list<CBase> *TPBaseList __attribute__((__may_alias__));

static void DoSomethingWithList(TPBaseList list)
{
  std::list<CBase>::iterator it;
  //
  std::cout <<"size="<< list->size() << " max size=" << list->max_size() << std::endl;
  for (it=list->begin(); it != list->end(); it++)
    it->Print();
}

#define arrsize(x) sizeof(x)/sizeof(x[0])

int main (const int argc, char *argv[])
{
  CBase bases[] = {CBase(1), CBase(2), CBase(3)};
  std::list<CBase> base_list (bases, bases + arrsize(bases));
  
  CDerived deriveds[] = {CDerived(4.2), CDerived(5.2), CDerived(6.2), CDerived(7.2)};
  std::list<CDerived> derived_list (deriveds, deriveds +arrsize(deriveds));
  
  DoSomethingWithList((TPBaseList)&base_list);
  DoSomethingWithList(reinterpret_cast<TPBaseList>(&derived_list));
  return 0;
}


which compiled great under my local gcc 4.7.2
 g++ -O3 strict_aliasing.cpp -Wall -Werror


But under remote gcc 4.1.2 i faced with

dereferencing type-punned pointer will break strict-aliasing rules


I've read many topics concern that like:
http://stackoverflow.com/questions/4163126/dereferencing-type-punned-pointer-will-break-strict-aliasing-rules-warning
http://cellperformance.beyond3d.com/articles/2006/06/understanding-strict-aliasing.html
http://stackoverflow.com/questions/98650/what-is-the-strict-aliasing-rule/99010

and conclude that i could somehow turn it off for a particular type. Because i want leave -O3 i cannot simply turn off strict aliasing globally via

g++ fno-strict-aliasing -O3 strict_aliasing.cpp -Wall fno-strict-aliasing



How to do that in my case?

----
Workaround for this moment is just downgrade optimization to O1 level.

Last edited on
Forcing that to compile without warning won't make this program valid. Why not do it right and make DoSomethingWithList a function template accepting a pair of iterators? Or, if you're looking for runtime polymorphism, have a list of pointers to base.
Last edited on
Cubbi, my workaround is not about suppressing warning , it's just should suppress strict aliasing at all.
About code: originally is not mine and implemented in third party library in such way
Topic archived. No new replies allowed.