On Apr 14, 2013, at 10:51, Jens Alfke <[email protected]> wrote:
> C++ static initializers are evil, though, at least the ones that run code.
> They run super early, in an undefined order, with no way to specify
> dependencies between them; so if you’re not careful they can slow down launch
> and/or cause weird nondeterministic bugs.
That would be when declared in the file scope. You can give them function scope
which means they are not initialized before entering the function, and with
C++11 this is thread-safe (though in practice it was also thread-safe before,
unless you disabled it).
So the way to do this would be to wrap your C++ global object in a function
much like the sharedInstance idiom of Objective-C:
MyPreferences& global_preferences ()
{
static MyPreferences instance;
return instance;
}
In Objective-C++ you can do something like the above when implementing
sharedInstance:
+ (MyPreferences*)sharedInstance
{
static MyPreferences* instance = [MyPreferences new];
return instance;
}
This gives you a lazily constructed singleton object.
> (I have spent time on at least one huge C++ project ripping out all static
> initializer functions/constructors, for exactly those reasons.)
As indicated above, the unpredictable construction order can be solved by
avoiding the file scope, though one issue which remains is that static objects
will be destroyed during program termination, and this happens without any
implicit cancellation of running threads. So if you have a global object shared
with other threads, you should use heap storage or ensure all threads (that may
use it) has finished before terminating the application.
A simple way to change to heap storage and still get the lazy thread-safe
construction is something like:
MyPreferences& global_preferences ()
{
static auto instance = new MyPreferences;
return *instance;
}
It is however a nice feature to have all your objects destroyed at program
termination.
_______________________________________________
Cocoa-dev mailing list ([email protected])
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com
This email sent to [email protected]