Is this illegal/dangerous?
int* static_nonew()
{
static int n = 5;
return &n;
}
The compiler doesn't seem to have a problem with it, but is the pointer location itself protected from being overwritten when someone else needs memory?
EDIT: A little bit more of an explanation of why I asked this question. Note: I'm programming in C++, I just tagged it as C because it seemed to be more of a C than C++ question.
I have a class that's supposed to return a static map. I only want this map initialized once throughout the program as there doesn't seem to be a need to do it multiple times. For this reason, I was going to have something like this:
static std::map<std::string, Transition*> transitions;
static Transition trans1(transitions, ...);
static Transition trans2(transitions, ...);
return &transitions;
The Transition classes constructor would add itself to the transitions. In that way, it would create the transitions once and then return a pointer to them. I just remember that if you create a reference to a variable allocated on the stack, it could get overwritten very easily and was "unsafe". I was just a bit confused with exactly how static variables created within a function work.