C++ 的寿命是多少?数据结构对象?
假设我有一个 Car.h
,它定义了一个名为 Car 的类,并且我有实现 Car.cpp ,它实现了我的 类 Car
,例如我的 Car。 cpp
可以是:
struct Helper { ... };
Helper helpers[] = { /* init code */ };
Car::Car() {}
char *Car::GetName() { .....}
助手数组的生命周期是多少? 我需要说 static Helper helpers[];
吗? 如果我做了一些不好的做法,请告诉我。
Suppose I have have a Car.h
which define a class called Car , and I have implementation Car.cpp which implement my class Car
, for example my Car.cpp
can be :
struct Helper { ... };
Helper helpers[] = { /* init code */ };
Car::Car() {}
char *Car::GetName() { .....}
What is the life time of the helpers array ?
Do I need say static Helper helpers[];
?
If I have done some bad practices, please let me know.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在全局/命名空间范围内声明/定义的任何变量都有完整的生命周期,直到代码结束。
如果您希望您的
Helper helpers[];
只能在Car.cpp
中访问,那么只有您应该将其声明为static
;否则让它成为一个全局的。换句话说,编辑:正如@andrewdski 在下面的评论中建议的那样;您应该将
helpers[]
设置为static
变量,因为您在此文件中使用它;即使Helper
在外部不可见。在 C++ 中,如果两个完全不同的单元具有相同的命名全局变量,那么编译器会通过将它们引用到相同的内存位置来默默造成混乱。Any variable declared/defined in global / namespace scope has a complete life time until the code ends.
If you want your
Helper helpers[];
to be accessible only withinCar.cpp
then only you should declare it asstatic
; otherwise let it be a global. In other words,Edit: As, @andrewdski suggested in comment below; you should make
helpers[]
asstatic
variable since you are using it within this file; even thoughHelper
is not visible outside. In C++, if 2 entirely different unit has same named global variables then compiler silently create a mess by referring them to the same memory location.在文件范围定义的对象称为静态存储持续时间对象。
在大多数情况下,您可以将它们视为在进入 main() 之前创建并在退出 main() 后销毁(有例外,但我不会担心)。
静态存储持续时间变量的销毁顺序与创建顺序相反。
同一编译单元(文件)内的创建顺序就是它们的声明顺序。
Static Storage Duration
对象的创建顺序。Objects defined at file scope are called
Static Storage Duration
objects.In most situations you can think of them as being created before main() is entered and destroyed after main() is exited (there are exceptions but I would not worry about that).
The order of destruction of static storage duration variables is the reverse order of creation.
The order of creation within the same compilation unit (file) is the order they are declared.
Static Storage Duration
objects across different compilation units.