1

変数のアドレスバインディングを読んでいて、実行中に変数のアドレスが変更されるかどうか疑問に思っていましたか?JVMまたはCLRでのガベージコレクションが原因で発生する可能性はありますか?そして、CとC ++はどうですか?

4

7 に答える 7

3

If your code has Undefined Behaviors then all bets are off and yes it might happen.
But in a valid C/C++ program the address of an variable will not change.

于 2012-05-22T05:29:45.790 に答える
3

This depends greatly on the language and what you mean by change the address. In C++ the address of an object is what uniquely identifies it and they cannot be moved. Some managed languages (including Java and C#) use generational garbage collectors that actually move the objects around in memory (in a generational GC, object will move from one generation to another with time), but the fact is that you should not care: In those languages that you can obtain the address of the object, the address is fixed, in those where the address is fixed, it is not part of the perceivable state of the object...

Also note that I am using object, rather than variable here, as I believe this is what you are interested on. There is a fine line that separates objects and variables, for example, in Java, a reference is a variable that can be used to access an object. But I won't even try to go into the precise definitions of either...

于 2012-05-22T05:51:00.523 に答える
1

In a valid C/C++ program unless your code changes the address of the variable deliberately or otherwise, the address will not be changed by the execution environment.

于 2012-05-22T05:36:34.197 に答える
0

基本的に、変数はプログラムの実行時に同じ値またはメモリ位置を参照し続けます。ただし、これは変更してuninitialized(未定義の値を持つ)作成できるため、特定の値を明示的に指定する必要があります。これにより、予測できない結果が生じる可能性があります。このような問題を処理するために、メモリ内の変数に必要なスペースは、変数が最初に使用されたときにのみ割り当てられ、不要になったときに解放されます。

于 2012-05-22T06:15:41.213 に答える
0

It's not likely to change but don't base your code around the assumption that it won't.

于 2012-05-22T05:40:39.193 に答える
0

In Java, the address of some kinds of variables can change (e.g. static or instance fields), and others typically can't (e.g. local variables). For current generation JVMs, thread stacks live in memory segments outside of the heap, and the GC does not move them.

However, this is moot with respect to "taking the address of a variable", because you can't do that in Java. (If you could, then it would be the responsibility of GC to deal with relocation.)

于 2012-05-22T05:43:18.057 に答える
0

In c++ the address won't change.

Be aware that in c++ you can override the & operator though for variables of class tyoe, so even though the address won't change, the value you might get from &variable might change (which isn't the address changing but might be confusing)

于 2012-05-22T07:58:07.937 に答える