On 12/18/2016 12:15 PM, Eduardo Yÿffffffffffe1nez via gcc-bugs wrote:
>I wish to report a problem with g++ 4.x, g++ 5.x, g++ 6.x. I'm trying >to implement a very classic Factory Method Pattern in C++, I can do it >very easily in MS-Visual C++, but in Linux with g++ the code compiles >but I get a segmentation fault when I run it. The code is very simple >to follow and I reduced it to a very academic code example to try to >diagnose the problem. I am building with the C++11 version.

It looks like a global static initializer ordering problem. You have two variables with static initializers: TResourceMap Factory::registry and BrandsFactory BrandsFactory::createThisFactory. The initializer for createThisFactory is referring to the registry variable. If the initializer for createThisFactory runs first, then it is referencing an uninitialized variable, and the code crashes.

Order of global static initializers is probably unspecified or undefined. I don't have a copy of the C++ standard handy.

I can reproduce the problem on linux if I put brands.cpp before resourcefactory.cpp on the link line. The code works if I put brands.cpp after resourcefactory.cpp on the link line. Changing the link order is changing the static initializer order.

Jim

Reply via email to