Problem with Static Variables

Discuss the development of new homebrew software, tools and libraries.

Moderators: cheriff, TyRaNiD

Post Reply
coolkehon
Posts: 355
Joined: Mon Oct 20, 2008 5:44 am

Problem with Static Variables

Post by coolkehon »

i'm using c++ and when i declare a static variable in a class it sometimes looses its values.
most of the time when it happens when i'm using it to store a pointer and it crashes the psp most of the ime because i check to see if it is null and it isnt but it doesn't point to the right object anyone have any ideas why because this screw up singelton
m0skit0
Posts: 191
Joined: Tue Jun 02, 2009 8:58 pm

Post by m0skit0 »

Maybe the compiler is optimizing the code and that messes your algorithm. Tried "volatile" keyword?
The Incredible Bill Gates wrote:The obvious mathematical breakthrough would be development of an easy way to factor large prime numbers.
coolkehon
Posts: 355
Joined: Mon Oct 20, 2008 5:44 am

Post by coolkehon »

couldn't use volatile with a static variable

Code: Select all

Icon.h
class Icon
{
     pulbic:
             Icon();
             static Text * iconText;
}

Icon.cpp
Text * Icon::iconText = NULL;

main.cpp
Icon::iconText = new Text(blah,blah);
while(true)
{
uses text.
 works for a while then stops randomly for no reason and crashes because pointer is not valied for some reason
crashes because the pointer is not null and it is not valid
}
m0skit0
Posts: 191
Joined: Tue Jun 02, 2009 8:58 pm

Post by m0skit0 »

You shouldn't declare an attribute as public, that violates encapsulation. I guess you're messing with the pointer and that's the result. Better declare the iconText attribute as private and access it through a method. Make sure this method manipulates rightly the attribute.

Anyway, I dont see why would you declare an attribute static. That's usually done for function's local variables, so they keep the value between calls.
The Incredible Bill Gates wrote:The obvious mathematical breakthrough would be development of an easy way to factor large prime numbers.
coolkehon
Posts: 355
Joined: Mon Oct 20, 2008 5:44 am

Post by coolkehon »

in this instance i declaired iconText static because i had a collection of icons and each would tell the text to change its text and center it. All icons were to use the same text i have since fixed this and given each a local variable pointing to this text. As for the singleton issue it still crashes and the _instance pointer is/was already private
Post Reply