首页 > 解决方案 > 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();
   ...
 }
}

标签: c++

解决方案


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()


推荐阅读