重载函数中的静态变量
我有一个执行以下操作的函数:
- 当调用函数并传递 true bool 值时,它将静态 bool 值设置为 true
- 当调用函数并传递字符串时,如果静态 bool 值设置为 true,它会对该字符串做一些事情
这是我关心的问题——静态变量在两个重载函数之间会保持不变吗?如果没有,我可以简单地创建一个单独的函数来跟踪 bool 值,但我尽量让事情变得简单。
I have a function which does the following:
- When the function is called and passed a true bool value, it sets a static bool value to true
- When the function is called and passed a string, if the static bool value is set to true, it will do something with that string
Here is my concern -- will a static variable remain the same between two overloaded functions? If not, I can simply create a separate function designed to keep track of the bool value, but I try to keep things simple.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
两个重载函数是两个不同的函数。即使每个函数都包含具有相同标识符的
static bool
,它们也属于不同的作用域,并且标识符引用每个函数中的不同变量。如果您需要在两个函数之间共享状态,您最好创建一个类来封装此状态并使这两个函数成为此类的成员函数。
Two overloaded functions are two different functions. Even if each function contains a
static bool
with the same identifier, they belong in different scopes and the identifier refers to a distinct variable in each function.If you need to share state between two functions you are probably better off making a class to encapsulate this state and making the two functions member functions of this class.
不,它创建两个单独的静态变量 - 每个函数一个。任何 C++ 函数的名称都是由其表观名称及其参数类型组成的,并且静态名称(至少在概念上)附加在其上。您可以考虑将变量相对于包含函数的类设为静态,而不是添加另一个函数,尽管这不会为您提供完全相同的行为,或者将其放置在匿名命名空间中
: :
No, it creates two separate static variables - one for each function. The name of any C++ function is made op of its apparent name and its parameter types, and the name of the static is (conceptually at least) tacked on to that. Rather than add yet another function, you could consider making the variable static with respect to the class containing the functions, although this does not give you exactly the same behaviour, or place it in an anonymous namespace:
To make the functions members of a class:
答案是否定的。没有理由这样做,因为毕竟我们谈论的是两个函数。
既然已经被演示过,我想解决问题的核心:
static
。static
引入了全局状态,而全局状态是邪恶的。它会导致微妙的错误,难以正确测试(因为测试会影响其后执行的测试),甚至不要考虑在那里进行多线程......因此,我真的鼓励您避免
static
完全。然后,您将有 2 个解决方案:选择更容易实现的那个。
The answer is no. There is no reason it should be, since after all we are talking about 2 functions.
Since it's already been demonstrated, I'd like to address the very core of the matter:
static
.static
introduces global state, and global state is evil. It leads to subtle bugs, difficulties to test properly (since a test affects the ones executed after it) and don't even think about going multithreaded there...Therefore I would really encourages you to avoid the
static
entirely. You would then have 2 solutions:Pick up whichever is easier to achieve.