Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using constructors of global objects for initialization is risky #254

Open
zzxx-husky opened this issue Feb 23, 2017 · 2 comments
Open

Using constructors of global objects for initialization is risky #254

zzxx-husky opened this issue Feb 23, 2017 · 2 comments
Assignees
Labels

Comments

@zzxx-husky
Copy link
Collaborator

The assumption of SessionLocal is that all global objects will be automatically and fully initialized (allocated and constructed) at the beginning of the whole program (before main() is invoked). But this is not practical.

As stated in C++ standard:

Objects with static storage duration (3.7.1) shall be zero-initialized (8.5) before any other initialization takes place. Zero-initialization and initialization with a constant expression are collectively called static initialization; all other initialization is dynamic initialization.

And also

It is implementation-defined whether or not the dynamic initialization (dcl.init, class.static, class.ctor, class.expl.init) of an object of namespace scope is done before the first statement of main. If the initialization is deferred to some point in time after the first statement of main, it shall occur before the first use of any function or object defined in the same translation unit as the object to be initialized.

(From StackOverflow)

In short, constructors of global objects are dynamic initialization and dynamic initialization is not guaranteed to be done before main(), but is guaranteed before the first call.

One solution to this is, for each thing that needs to be initialized, initialize it at the first time it is used. Meanwhile, if it needs to be finalized, register a finalizer when it's initialized. The finalizer is called at the end of the program.

@zzxx-husky zzxx-husky added the bug label Feb 23, 2017
@zzxx-husky zzxx-husky self-assigned this Feb 23, 2017
@kygx-legend
Copy link
Member

If finalization can be combined with husky::Context as an interface, it would be better.

@zzxx-husky
Copy link
Collaborator Author

@kygx-legend Agree. Register finalizer to husky::Context.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants