4

So the code mentioned on the topic line causes segmentation fault with Qt 4.8.3 & gcc 4.7.2

This is at outside of any classes/structs at .cpp-file and works with gcc 4.4

const QList<int> warnings = QList<int>() << 0 << 3 << 7;

Traces gives these two hints:

__do_global_ctors()
__static_initialization_and_destruction_0

So it seems that "warning" is not yet available when its inserting latter list into it.

Works with 4.7.2 if i change it into this:

global scope: QList< int> warnings;

This is inisde some function:

warnings = QList<int>() << 0 << 3;

I'm wondering why this happens?

Edit:

I guess i clipped a bit too much stuff out from my question originally, but warnings is supposed to be const at file scope (.cpp-file) for holding bunch enums.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
turska
  • 61
  • 6
  • 1
    This may seem very trivial. Is the expression solved as `const QList warnings = (QList() << 0 << 3 << 7);`, right? – Acorbe Nov 07 '12 at 13:38
  • Moreover, what about `const QList warnings = QList << 0 << 3 << 7;`? (No parentheses to call constructor.) – Acorbe Nov 07 '12 at 13:44
  • That would be pretty much the same as writing `int i = int << 1;` Won't compile. – jrok Nov 07 '12 at 13:46
  • indeed I am still wondering [how can one achieve that](http://ideone.com/Qh2RXP) using temporary objects.. – Acorbe Nov 07 '12 at 14:00
  • By ending the class definition with a colon? http://ideone.com/dVFBWf :) – jrok Nov 07 '12 at 14:07
  • @jrok, LoL I was going crazy.... :)... Btw, the definition `a operator<< (a t, const int j) { t.i = j; return t; };` can't use `a&`, which you need to iterate the `<<`..right? – Acorbe Nov 07 '12 at 14:14
  • I'm not sure what you mean by "iterate", but `operator<<` overload should return (and take) a reference, so you call it on the same instance when chaining. – jrok Nov 07 '12 at 14:20
  • @jrok, that is right; although that won't work in the current ideone example because you cannot reference temp objects [consider this](http://ideone.com/uN1duJ) – Acorbe Nov 07 '12 at 14:25

1 Answers1

6

My psychic debugging powers tell me that the line in question exists at global/file scope, not at class/function scope. Thus your line may be called at any point during static initialization. With your old gcc it just so happened that QT was initialized before your line was called. With the new gcc it reordered (perfectly legal) the static init to call your function first, before QT was ready to create objects and insert into them.

The solution is to hold off on creating that QList until after main starts. Using pointers or static local objects are two common implementations.

Mark B
  • 95,107
  • 10
  • 109
  • 188
  • I think you are right. With those two (do_global_ctors..) functions at the stack its doing the static initialization for global/file scope.Too bad that the code base i inherited is full of const qlist's like that one. – turska Nov 07 '12 at 15:44