Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

tscott1213

Static vs. Global Object Creation

This topic is 5715 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hey gang, I have two questions. 1) I am using Microsoft''s VC++ compiler, is it not possible to step through code in an object''s constructor? Typically, when I am debugging my code, I run to a specific line in the code and then step through to examine variables and whatnot. However, I don''t seem to be able to do this in any of my constructor functions? 2) This one is a bit tougher (for me at least). I have an object with a static data member. The static data member is a list of pointers to all of the objects that that have been created. Let''s call this obj_w_static. I have another object that is instatiated globally. The constructor for this global object creates an obj_w_static object and calls one of its member functions. The member function attempts to use the static data member, but it appears taht the static data member has not been created yet. So two questions: a) Is what I am describing possible or have I misread the problem. b) Is there a way to force the static variable to be created first? Thanks Todd

Share this post


Link to post
Share on other sites
Advertisement
AFAIK, the only requirement for such objects is that all global/class static objects must be created before main is entered. Their order is indeterminate. But there is a loophole, though it is clumsy. The loophole is this. If a variable is static to a function (not a class), then that variable is constructed when that function is first called. So if you have data, you can hide it thusly.


  
FirstStaticGroupOfData& getFirst(void)
{
static FirstStaticGroupOfData data;
return data;
}

SecondData& getSecond(void)
{
static SecondData data;
return data;
}


Now to access the static data you just call getFirst() or getSecond() to change or whatever to it.

But you can be sure that whenever one of those functions is called to access the data, the object will have been constructed by the time you access it.

This is less convenient than holding data in simple global variables or static class stuff, but it is the only straightforward way of setting the order.

See "Effective C++" by Scott Meyers, Item 47 (which starts on page 219 in my copy) for a full discussion of this issue.

-D

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!