c++ - Static local variable and auto
问题描述
In the code snippet below, is the local variarble result1 static? Is the keyword static mandatory do declare a static local variable or would auto suffice?
static int ExpensiveInit() {
...
}
class Foo {
void Bar() {
auto result1 = ExpensiveInit();
static int result2 = ExpensiveInit();
...
}
}
解决方案
You declare a class attribute static
when you want all instances of your class to share the same value of this variable, it is useful to count how many instances of a class you have for example.
Therefore by stating
static int count = 4;
As an attribute of your class, every instance will have access to this variable, and if an instance increment count
, it will increment this variable for other instances aswell
Auto declaration means that the type of variable will be automaticaly assigned by the compilator, as long as it is coherent.
If you state :
auto hello = "Hello";
Hello is considered as a String
Thus, no, result1 is not Static in your example, it is a simple int, in wich is copied the value returned by expensiveInit()
推荐阅读
- asp.net-mvc - Remote Validation On Nested ViewModels With __RequestVerificationToken
- c - Printf 和 scanf 不能正常工作?C 编程
- office365 - 创建带有变体的 PowerPoint 模板 - 搜索 Microsoft 的 Variant Creator
- java - ObservableList 返回匹配的子列表
- python - 通过网页按钮终止 PiCamera 捕获
- macos - 正在链接旧的 lapack .dylib 而不是当前版本
- javascript - 属性指令不适用于 ajax 加载的元素?
- r - 如何使用 R 进行基因表达数据集分析
- html - 搜索栏,html css。(原子用户)
- spring-webflux - spring webflux如何获取整个请求体?