大家讲道理2017-04-18 09:24:33
Initialized variable points:
Declare variables
Assign a value to a variable
Allocating memory is also divided into:
Allocate memory in the heap
Allocate memory on the stack
So, this question is relatively general.
First of all, here’s a chestnut:
int a;//分配jvm中的栈内存,形成一个引用
a = 1;//分配jvm中的堆内存
Another example:
String str = new String(“hello”);
str This reference is placed on the stack
The object instance created by new is placed on the heap
The literal value "hello" is placed in the static storage area
Continue with the chestnut above:
String str1 = str;//此时,str1也是一个引用,放在栈上。指向堆里的hello
If you want to know more, you can read one of my columns. At the beginning, we briefly talked about the Java Memory Model.
巴扎黑2017-04-18 09:24:33
That’s not right.
int i; //At this time, space is allocated for variable i, and i has a value
i=1; //Assignment
Initialization is just giving a meaningful value to this variable.
巴扎黑2017-04-18 09:24:33
Initializing a variable means allocating memory for this variable. Is this correct?
That’s not true, at least in C++.
According to my understanding, in C++, to use a variable, the following three steps are generally required:
Declaration
"Declaration" can introduce identifiers used by variables, but it does not allocate memory space. For example, the identifier extern int i;
,表示i
will be an integer in the subsequent program.
definition
In addition to introducing the identifier used by the variable like the declaration, "definition" will also allocate the corresponding space according to the type of the variable, but will not be initialized (more accurately, "default initialization" will be performed. see below). For example int i;
,就定义了一个整型变量i
and allocate space to it.
Initialization
"Initialization" means assigning a value to a variable when it is defined. For example, int i = 1;
,就定义了一个整型变量i
and allocate space for it, and set its value to 1.
A little explanation about the "default initialization" above:
"Default initialization" (default initialization) is simply a process. When using T x;
定义变量时,如果T
是一个类,就调用这个类的默认构造函数来初始化x
,如果T
is a built-in type, no initialization is performed. For more details, please refer to the regulations in the C++ standard.
黄舟2017-04-18 09:24:33
Not entirely correct, static in C++ objects will not allocate memory first
巴扎黑2017-04-18 09:24:33
It’s not right in Java,
Object o;//This also allocates memory, allocates the memory of the object o,
o = new Object(); //Initialization, referenced object
伊谢尔伦2017-04-18 09:24:33
That’s wrong
Generally, space is allocated to a variable when it is defined, while initialization is to assign an initial value to this space, which is not necessary. The two are not equivalent
阿神2017-04-18 09:24:33
Incorrect. Generally speaking, initializing a variable is just to make the variable meaningful. If it is meaningful, you can perform related operations