在 C++ 中将向量声明为全局变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7557585/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Declaring vector as global variable in C++
提问by cpp_noname
Is it a good practice to declare a vector as global in C++?
在 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.
请指教。
回答by cpp_noname
My program compiles successfully, but I am not sure whether this could lead to a runtime error under certain circumstances.
我的程序编译成功,但我不确定在某些情况下这是否会导致运行时错误。
This is safe to do; the storage for the vec
variable will be allocated statically and its default constructor will be called at some point (exactly when within the context of your entire program is not strictly defined, as order of initialization across translation units is not strictly defined).
这是安全的;vec
变量的存储将被静态分配,并且它的默认构造函数将在某个时候被调用(正是在整个程序的上下文中没有严格定义时,因为跨翻译单元的初始化顺序没有严格定义)。
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.
并且编译器可能会保留有限的内存量,该向量可以扩展到该内存量。达到此限制后,正在写入的内容可能会占用另一个变量使用的内存。
The vector itself allocates its storage on the heap, so there will be no limitations imposed upon its expansion that would be different if you instantiated the vector as a local variable: you're basically going to be limited by the amount of memory you can contiguously allocate at the points in time the vector needs to reallocate its internal storage.
向量本身在堆上分配其存储空间,因此如果您将向量实例化为局部变量,则不会对其扩展施加任何限制:您基本上将受到可以连续使用的内存量的限制在向量需要重新分配其内部存储的时间点分配。
All of that said, while this is safe to do so, it isn't necessarily good practice; it falls into the domain of every other global variable or globally-accessible bit of storage, which can be a bit of a contentious subject. Generally, I would advise that it is preferable to avoid global variable as a rule. While it may be acceptable in some cases, the global access runs counter to your ability to control the access to the variable and enforce invariants on it and the state it controls or implies. This can lead to difficult-to-maintain systems as a codebase scales because those access paths are not clearly spelled out.
综上所述,虽然这样做是安全的,但不一定是好的做法;它属于所有其他全局变量或全局可访问的存储位的域,这可能是一个有争议的主题。通常,我建议最好避免使用全局变量。虽然在某些情况下它可能是可以接受的,但全局访问与您控制对变量的访问并对其实施不变量及其控制或暗示的状态的能力背道而驰。随着代码库的扩展,这可能导致难以维护的系统,因为这些访问路径没有明确说明。
回答by Nawaz
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.
根据我的理解,全局变量的内存会在编译时分配,编译器可能会保留有限的内存量,这个向量可以扩展到。
This is wrong understanding.
这是错误的理解。
Memory is not allocatedat compile time. Memory is allocated at the program startup, and then duringthe program, depending on the storagetypes of variables. And when the program shutdowns, all the memory used by it returns to the OS, no matter what.
编译时不分配内存。内存在程序启动时分配,然后在程序期间分配,具体取决于变量的存储类型。当程序关闭时,它使用的所有内存都归还给操作系统,无论如何。
Upon hitting this limit, what is being written can eat into the memory used by another variable.
达到此限制后,正在写入的内容可能会占用另一个变量使用的内存。
No. An object of std::vector<int>
can never eat memoryused by another variable(s).
不。一个对象std::vector<int>
永远不能占用另一个变量使用的内存。
Now coming back to your main question,
现在回到你的主要问题,
Is it a good practice to declare a vector as global in C++?
在 C++ 中将向量声明为全局是一个好习惯吗?
No. Avoid global variables, irrespective of their types.
不。避免使用全局变量,无论它们的类型如何。
回答by Ben Voigt
Only the space for the vector metadata will be allocated in the area for global variables. The vector contents will still be dynamically allocated (constructors and destructors run normally for global variables).
全局变量区域中只会分配向量元数据的空间。向量内容仍将动态分配(构造函数和析构函数对于全局变量正常运行)。
It's the same situation for an automatic vector variable, like:
自动向量变量的情况相同,例如:
int main(void)
{
std::vector<int> v;
return 0;
}
There's a limit to the stack space available for automatic variables, but the vector contents won't use this space, only a handful of pointers and counters.
可用于自动变量的堆栈空间是有限的,但向量内容不会使用这个空间,只有少数指针和计数器。
回答by istudy0
Well, vec is a global variable, so the memory for it is presumably allocated from the data segment. However, the memory for the contents of vec depends on the allocator. By default, I think that the memory for the contents is allocated from the heap.
嗯, vec 是一个全局变量,所以它的内存大概是从数据段分配的。但是,vec 内容的内存取决于分配器。默认情况下,我认为内容的内存是从堆中分配的。
回答by MGZero
Global variables in general are bad practice. They won't "eat" into memory of another variable as you say, however, it's very easy for you as the programmer to screw something up. For example, everything in the program has access to this vector and so everything can access and modify it. You may or may not want this, but more than likely, you don't want this.
全局变量通常是不好的做法。他们不会像你说的那样“吃掉”另一个变量的内存,但是,作为程序员,你很容易把事情搞砸。例如,程序中的所有内容都可以访问该向量,因此所有内容都可以访问和修改它。您可能想要也可能不想要这个,但更有可能的是,您不想要这个。
As for memory allocation, objects added to the vector are still added on runtime (because they don't exist on compile time!). Memory is also never allocated at compile time. Your program has the signature in it to allocate this memory at RUN time. Think about that...if the program allocated memory at compile time, you wouldn't really be able to run them on other machines would you? The memory would be allocated on YOUR machine, but not on other machines. Hence, memory must be allocated on run time.
至于内存分配,添加到向量的对象仍然会在运行时添加(因为它们在编译时不存在!)。在编译时也永远不会分配内存。您的程序中包含在运行时分配此内存的签名。想想看……如果程序在编译时分配内存,你就不能在其他机器上运行它们,对吗?内存将分配在您的机器上,而不是其他机器上。因此,必须在运行时分配内存。
回答by Pubby
Your program doesn't allocate anything during compile-time - I think you mean run-time.
你的程序在编译时没有分配任何东西 - 我认为你的意思是运行时。
Vector allocates what it holds on the heap (vec.size() * sizeof(/* what you are holding*/)) - it holds sizeof(std::vector<>) on where it is allocated. Global variables may be stored anywhere, it depends on the implementation.
Vector 分配它在堆上持有的东西 (vec.size() * sizeof(/* 你持有的东西*/)) - 它在分配的地方持有 sizeof(std::vector<>) 。全局变量可以存储在任何地方,这取决于实现。