Search code examples
c++g++segmentation-faultbooleaninitialization-list

C++ 11 Segfault with several bools in initialization list


I wrote a simple class Actor with ints and a lot of bool members:

Here's an exerpt from the actor.cpp file

 Actor::Actor ()     
:X(0),Y(0),W(14),H(14),speedX(0),speedY(0)
,left(false),right(false),up(false),North(false),
East(false),South(false),West(false),NorthEast(false),
NorthWest(false),SouthEast(false),SouthWest(false){}

...

And that's from the actor.h header file

class Actor
{
 private:
    int X;
    int Y;
    unsigned short int W;
    unsigned short int H;

    unsigned short int speedX;
    unsigned short int speedY;

    bool left; 
    bool right; 
    bool up;

    bool North; 
    bool East; 
    bool South; 
    bool West; 
    bool NorthEast; 
    bool NorthWest; 
    bool SouthEast; 
    bool SouthWest;     
 public:        
    Actor();
    ~Actor();

This compiles without any Errors,

but if I run the program, I get a weird segfault right in the beginning.

Now If I put all the bools in the initialization list into comments (//,left(false)) and get gcc to compile everything, the program runs perfectly!

What is wrong? I thought it's better to init all class members via the initialization list.

Could this be a g++ bug?

I've already tried using left() instead of left(false). And no: I'm not using new- or *- operators in my program anywhere!


Solution

  • First, "I get a weird segfault right in the beginning" is not even close to an error description. So please post the exact error. Also since you said "found a bug in gcc", gcc is currently at version 4.8. So unless you tell which compiler and what version of that compiler you are using, debugging is useless.

    Second, initialization lists are useful when you have inheritance and want some special behaviour on base class part and/or some member initializations. Its also useful if you have objects in the class which have a heavy constructor and correspondingly heavy copy constructor and operator=, in that case you can invoke the required constructor in the initializer list and save on doing a copy in the constructor code because otherwise, first the object would be created and then you would have to do some initialization.

    Third, for POD types, unless you have some weird inheritance issues, doing assignment in the constructor code should be fine.

    Finally, http://pastebin.com/x5tuvBFw is the code, with file names and it compiles and runs fine on gcc4.7 (and I guess even earlier versions)