I have a piece of code structured like this:
a.cpp:
#include "b.hpp"
const unsigned a = create(1);
b.cpp:
map<int, string> something; // global variable
unsigned create(unsigned a){
something.insert(make_pair(a, "somestring"));
return a;
}
Now, this throws out a segfault, valgrind says that map was not yet created. How does it work, how should I change it?
Variables that are created outside of a function (as in all of the examples above) are known as global variables. Global variables can be used by everyone, both inside of functions and outside.
A global variable is defined outside all functions and it accessible to all functions in its scope. A global variable can be accessed by all functions that are defined after the global variable is defined.
You can declare global—that is, nonlocal—variables by declaring them outside of any function definition. It's usually best to put all global declarations near the beginning of the program, before the first function. A variable is recognized only from the point it is declared, to the end of the file.
Yes, all members of a are guaranteed to be initialised to 0. If an object that has static storage duration is not initialized explicitly, it is initialized implicitly as if every member that has arithmetic type were assigned 0 and every member that has pointer type were assigned a null pointer constant.
C++ does not define an order for when global variables are constructed during program startup. a
could be initialized first before something
gets constructed which would cause the problem above. When you start constructing global variables that depend on other global variables being initialized then you run into the classical static initialization order fiasco.
An easy way to fix your above scenario is to make something
static and move it into your create
function.
unsigned create(unsigned a)
{
static map<int, string> something;
something.insert(make_pair(a, "somestring"));
return a;
}
That will guarantee something
gets created on first call to create
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With