简体   繁体   English

C ++中的全局变量

[英]Global variables in C++

I am working with some C++ code that has a timer and the timer runs this: 我正在使用一些带有计时器的C ++代码,计时器运行此代码:

char buf[1024];
ZeroMemory(&buf, sizeof(buf));
somefunction(buf); // this put stuff into buf
otherfunction(buf); // this do stuff with buf

somefunction() does a web request and InternetReadFile() puts the data in "buf" somefunction()发出Web请求,InternetReadFile()将数据放入“ buf”

But I need to be able to read the previous buf the next time the timer is executed. 但是我需要能够在下次执行计时器时读取前一个buf。 How can I store buf in a global var and reassign it or make "buf" equal to the previously stored value if necessary? 如何将buf存储在全局var中,并在必要时重新分配它或使“ buf”等于先前存储的值?

If you don't have to deal with multiple threads accessing the timer action function simultaneously, you can make buf into either a static variable within the scope of the function, or a file variable in the anonymous namespace (or, if you are an unreformed C programmer like me, into a file static variable). 如果不必处理多个线程同时访问Timer操作函数,则可以将buf设置为该函数范围内的静态变量,也可以将其设为匿名名称空间中的文件变量(或者,如果您未更改,则为像我这样的C程序员,放入文件静态变量)。 You then make sure the code does not zero the memory until you know you don't want to look at the old data again. 然后,您确保代码不会将内存归零,直到您知道不想再次查看旧数据为止。

Either: 要么:

void timer_action(void)
{
    static char buf[1024];
    ...use buf carefully...
}

Or: 要么:

namespace {
char buf[1024];
}

void timer_action(void)
{
    ...use buf carefully...
}

If nothing else needs the buffer, hiding it inside the function minimizes the scope and is the preferred solution. 如果没有其他需要的缓冲区,则将其隐藏在函数中可将范围最小化,这是首选解决方案。

If you do have multiple threads involved, you have to be extremely careful, using appropriate thread synchronization primitives to ensure sequential access to the variable, or you have to make a per-thread copy of the variable in thread local storage. 如果确实涉及多个线程,则必须格外小心,使用适当的线程同步原语以确保对变量的顺序访问,或者必须在线程本地存储中为变量创建每个线程的副本。

Isn't something wrong if you require the old RAW data? 如果您需要旧的RAW数据是不是有问题? Instead extract the pieces of interest from the current RAW buffer and store as member variables in your class. 而是从当前RAW缓冲区中提取感兴趣的片段,并将其作为成员变量存储在您的类中。 For the next read, the relevant state is available. 对于下一次读取,相关状态可用。 State Design Pattern also could be helpful here if your code is about State transitions. 如果您的代码是关于状态转换的,那么状态设计模式在这里也可能会有所帮助。

This will help you avoid issues related to static variables as @Jonathan pointed out @Jonathan指出,这将帮助您避免与静态变量相关的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM