On 11/3/06, Andrew Haley <aph@xxxxxxxxxx> wrote:
Benjamin Grange writes: > On 11/3/06, Andrew Haley <aph@xxxxxxxxxx> wrote: > > Benjamin Grange writes: > > > Do you see a problem in this line?: > > > (void *) (unsigned long)(*(((unsigned int *)&a))); > > > > Yes, I can: it's not legal C++. What are you really tring to do that > > needs this? > I'm trying to make this code which is not from me to work with O3. > In the real code, there is a list class which use void * to save its elements. > A lot of other list are derived from this one to avoid doing casting > of void * to the original pointer. They all use real pointer, so no > problem. > But there is a special derived list which converts its elements > into int and save the int as a void * in order to avoid doing heap > allocation. Exactly like the code I have posted. If you know that the data will all fit within a void*, you can simply do class A { public: A(int n) { x = n; } int x; }; union { int n; void *p; } u; u.n = a.x; return u.p; ... or whatever, depending on your pointer size. > What make my code not legal C++? > > Will it be better if I do something like that for put(): > listA[i] = (void *)a.getInt(); > and get: > return A((int)listA[i]) OK, the rule is this: you cannot access an object of type A through a pointer that is not type compatible with A. So, if you declare: short *p; int a = 9; p = (short*)&a; return p; then your code will not work, and current versions of gcc will warn you: $ gcc /mnt/zebedee/p.c -O2 -Wall /mnt/zebedee/p.c: In function 'main': /mnt/zebedee/p.c:7: warning: dereferencing type-punned pointer will break strict-aliasing rules
Ok thank you. I will use the getInt() version since it's legal C++ and pointer size independent. -- Benjamin