3

In the project I am working I saw a code like below in code review process:

class A 
{
   shared_ptr<B> instanceB; 
}

A::A ()
{
   instanceB = make_shared<B>();
   static C localVariable(instanceB.get());
}

I know static variable's are like globals and will be created when program starts and instanceB will be created when A instantiated. And this may crash.

While explaining that I begin to think about what value instanceB.get() would return. Most probably garbage right? And when I think more about it I believe this code even shouldn't be compiled why static variables are allowed to take non-static parameters in their ctors?

1 Answer 1

8

and will be created when program starts

No, that's wrong. Static variables in functions are created when that function executes for the first time. Therefore, your localVariable will receive what instanceB.get() will return when A::A() will run for the first time. So no garbage will be in localVariable.

Such design might indeed look very strange, but it is syntatically correct and has a well-defined meaning for the compiler. Moreover, a very similar design is used in a classical singleton implementation.

Not the answer you're looking for? Browse other questions tagged or ask your own question.