Is it a good practice to declare a vector as global in C++? No. Avoid global variables, irrespective of their types.
You should typically not use global variables unless absolutely necessary because global variables are only cleaned up when explicitly told to do so or your program ends. If you are running a multi-threaded application, multiple functions can write to the variable at the same time.
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.
Is it a good practice to declare a vector as global in C++?
This is what I did.
#include <vector>
std::vector<int> vec;
My program compiles successfully, but I am not sure whether this could lead to a runtime error under certain circumstances. According to my understanding, the memory for a global variable will be allocated at compile time, and the compiler may reserve a limited amount of memory to which this vector can expand. Upon hitting this limit, what is being written can eat into the memory used by another variable.
Please advise.
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