开发者

init_priority attribute on variables in static libs

开发者 https://www.devze.com 2023-01-19 00:55 出处:网络
This is a new question after my long rant. The problem here is, I have a global vector<Base*> vObjs in my main application and I got Derived objs in each static lib linked to the application. If

This is a new question after my long rant. The problem here is, I have a global vector<Base*> vObjs in my main application and I got Derived objs in each static lib linked to the application. If I specify the vObjs to have an init_priority of 101 and each obj in static libs to have say... 1000, 开发者_运维百科is it guaranteed that vObjs will get its constructor called before objs in static libs? Thanks for any help.


Let me echo the other responses that you might want to reconsider using globals for this. However one possible (and I'm sure still flawed) improvement at least removes the need for init priority.

Instead of using a global vector, you create a function that returns a reference to a static local. The C++ rules make sure that the function static local is always initialized at the latest by its first use, so you don't have to worry about the vector not being initialized.

vector<LibInfo*>& get_gvLibInfo()
{
    vector<LibInfo*> gvLibInfo;
    return gvLibInfo;
}

Then your registration looks like:

vector<LibInfo*>& get_gvLibInfo();

void reglib()
{
    get_gvLibInfo().push_back(this);
}


Global Variables have been been considered harmful for nearly forty years and yet people still insist on using them. Why?

Please reconsider your design as it is brittle and is going to provide a maintenance headache for many years to come.


If you are using GNU C++, they seem to guarantee the order of initialization( click here ). However I should note that if you really rely on the order of initialization then your design is fragile. Better look for alternatives when you just don't care about the order. HTH

0

精彩评论

暂无评论...
验证码 换一张
取 消