C++ 的寿命是多少?数据结构对象?

发布于 2024-11-19 22:25:16 字数 344 浏览 9 评论 0原文

假设我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

谁人与我共长歌 2024-11-26 22:25:16

在全局/命名空间范围内声明/定义的任何变量都有完整的生命周期,直到代码结束。

如果您希望您的 Helper helpers[]; 只能在 Car.cpp 中访问,那么只有您应该将其声明为 static;否则让它成为一个全局的。换句话说,

Helper helpers[];        // accessible everywhere if `extern`ed to the file
static Helper helpers[];  // accessible only in `Car.cpp`

编辑:正如@a​​ndrewdski 在下面的评论中建议的那样;您应该将 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 within Car.cpp then only you should declare it as static; otherwise let it be a global. In other words,

Helper helpers[];        // accessible everywhere if `extern`ed to the file
static Helper helpers[];  // accessible only in `Car.cpp`

Edit: As, @andrewdski suggested in comment below; you should make helpers[] as static variable since you are using it within this file; even though Helper 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.

写给空气的情书 2024-11-26 22:25:16

在文件范围定义的对象称为静态存储持续时间对象。

在大多数情况下,您可以将它们视为在进入 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.

    • Note: There is no guarantee about the order of creation of Static Storage Duration objects across different compilation units.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文