Re: Static objects in statically linked libraries - are they constructed if not referenced elsewhere?
{ Top-posting is discouraged. So is quoting the clc++m banner. -mod }
Do this:
Have a factory singleton.
It should have a method like this:
bool Factory::GetInstance()->Register(key,
ObjectToBeCreated::Creator);
Creator being a static method which return an instance of the
ObjectToBeCreated.
In ObjectToBeCreated.cpp do this:
namespace {
const bool wasRegistered = Factory::GetInstance()->Register(key,
ObjectToBeCreated::Creator);
}
Makes sense?
That will solve your static problem.
Also, i recomend reading Alexandrescu's Modern C++ Design :-)
On Oct 31, 7:27 pm, "se...@roguewave.com" <se...@roguewave.com> wrote:
On Oct 31, 10:05 am, Tom Lynch <tfly...@gmail.com> wrote:
Suppose you have a typical abstract factory with a "registerCreator"
method that takes a type and pushes a type creator for that type into
some construction dispatch system invoked using "create(KeyType)".
The abstract factory is, as per usual, a global singleton.
If you create a library which contains a static object whose
constructor calls "registerCreator", and this static object is not
referenced anywhere in the main program, will it generally be linked
and constructed, registering the creator at runtime?
I've had a play and it seems the answer is no for my test cases, i.e.
the linker ignores the static objects I've defined in my libs.
The answer depends on the kind of library (archive vs. shared) and
on the platform. For archive (static) libraries, traditional UNIX
linkers avoid linking in the contents of entire .o files when none
of the symbols defined in them is used in the program they are being
linked with. Some modern linkers strip individual unused symbols even
if other symbols from the same .o are used. Sometimes such linkers
provide options (or pragmas) that let users control this behavior.
Objects linked into shared libraries cannot be not eliminated and
their ctors are usually run right after the library is loaded.
{ quoted clc++m banner removed -mod }
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]