gpt4 book ai didi

c++ - C++ 中的静态变量-vs- Objective-C

转载 作者:行者123 更新时间:2023-11-30 05:05:18 25 4
gpt4 key购买 nike

据我所知,对于 C++,关键字 static 在函数调用中意味着 static 变量在第一次声明时被初始化遇到

我在 Objective-C 成员函数中使用了 static 关键字,静态变量似乎立即被初始化(使用非编译时常量 subscriber) . 请注意,我正在使用 Objective-C 的混合文件类型 .mm 进行编码。

- (id) init
{
[self initSubsciber];
[self relayMessages];
}

- (void) initSubscriber
{
subscriber= PTR;
}

- (void) relayMessages
{
// Example 2-2 (mspoller.c), 0MQ book pg.43
// Initialize poll set
static zmq_pollitem_t items[] = {
{ subscriber, 0, ZMQ_POLLIN, 0 },
};

在上面的示例中,由于我在 relayMessages 之前调用了 initSubscriber,因此我希望 subscriber 成员变量指针等于 PTR ,而不是 NULL,因为尚未调用 zmq_pollitem_t 行。然而,它是 NULL

static 的行为在不同版本的 C++ 中是否发生了变化?并且,相比之下,Objective-C 中定义的行为如何?

最佳答案

不,C 没有改变。这就是您所期望的 C++ 的工作方式。

C

en.cppreference.com/w/c/language/storage_duration

Storage duration

[...]

  • automatic storage duration. [...]

  • static storage duration. The storage duration is the entire execution of the program, and the value stored in the object is initialized only once, prior to main function. All objects declared static and all objects with either internal or external linkage that aren't declared _Thread_local (since C11) have this storage duration.

C++

en.cppreference.com/w/cpp/language/storage_duration

Static local variables

Variables declared at block scope with the specifier static have static storage duration but are initialized the first time control passes through their declaration (unless their initialization is zero- or constant-initialization, which can be performed before the block is first entered). On all further calls, the declaration is skipped.

Objective-C++ (.mm)

.mm 是 Objective-C++,所以 C++ 应该适用。但这就是说没有官方的语言规范。因此,请务必移入 .cpp 文件并在 .mm 中仅保留一些接口(interface)代码。例如,不清楚线程安全的本地静态是否/如何工作 ( Is it possible to remove dispatch_once in Objective-C++? )。

What is Objective C++?

Also, you might want to read Apple's (sadly deleted, but archived) documentation on Objective-C++.

-- doches

Clang 有一个适用于所有 C 语言家族的通用统一解析器[ 5 ][ 6 ] 并且根据文件类型/扩展名和语言标准支持似乎激活了单个功能[ 7 ].

关于c++ - C++ 中的静态变量-vs- Objective-C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48460488/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com