sách gpt4 ai đã đi

c++ - 为什么可以修改函数内声明的静态 const 变量?

In lại 作者:行者123 更新时间:2023-12-01 19:26:36 26 4
mua khóa gpt4 Nike

我正在为我的游戏引擎实现一个 ECS 框架,并研究在运行时识别组件类型的方法。这意味着我可以在内存中连续动态地对相似类型的组件进行分组。例如,我可以为 PositionVelocity 组件设置两个单独的数组,我的系统可以循环使用它们。

我目前使用 typeid(),但我发现一篇文章使用 static const 变量为每种类型生成唯一的 ID。总体思路可以总结为下面的代码片段:

#include 

struct Position { float x, y; };
struct Velocity { float dx, dy; };

template
int test(int x) {
static const int y = x;
return y;
}

int main(int argc, char **argv) {
std::cout << test(1) << " ";
std::cout << test(2) << " ";
std::cout << test(3) << " ";
trả về 0;
}

这会输出1 1 3,但我希望由于它试图修改常量(特别是在第二次调用时),因此它将无法编译。为什么这有效?

1 Câu trả lời

静态变量仅初始化一次。

第二次(也是随后的)初始化被跳过。

这里还有两个不同的函数Bài kiểm tra。每个独特的模板参数类型 1 个。

示例,用于对您的代码进行简单的函数调用:

auto f() { return test(1); }

这将产生以下汇编代码,您可以在其中看到有一个检查来验证变量是否已初始化或返回已设置的值。如果尚未设置,则将以线程安全的方式设置。

f():
movzx eax, BYTE PTR guard variable for int test(int)::y[rip]
test al, al // <----- check if intialized
je .L13 // <----- if not initialized go to .L13
// otherwise return the value
mov eax, DWORD PTR int test(int)::y[rip]
trở về
.L13:
sub rsp, 8
mov edi, OFFSET FLAT:guard variable for int test(int)::y
call __cxa_guard_acquire
test eax, eax
jne .L14
mov eax, DWORD PTR int test(int)::y[rip]
add rsp, 8
trở về
.L14:
mov DWORD PTR int test(int)::y[rip], 1
mov edi, OFFSET FLAT:guard variable for int test(int)::y
call __cxa_guard_release
mov eax, DWORD PTR int test(int)::y[rip]
add rsp, 8
trở về

关于c++ - 为什么可以修改函数内声明的静态 const 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59800414/

26 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com