'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();
...
}
}
Solution 1:[1]
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 compiler, 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()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
