开发者

Declaring a reference is a regular instruction or just a second name?

When I write,

T &t = obj;

Is this considered an instruction (which generates machine code) or just a second name of开发者_开发百科 obj?


I don't think that the standard ever uses the word instruction, except for generated code. The line T &t = obj; is a declaration statement which is a definition; it's a statement, but so are things like using std::string;. It may or may not result in executable code being generated, depending on a lot of things.

Also (because of your title): there's no assignment in T &t = obj;.


That depends. If the optimizer is able to eliminate T altogether, then there won't be any machine code generated. Otherwise, there probably will be.

If you really care about the answer for some specific piece of code, compile the code as you would normally (same compiler, same optimization options etc), but get the compiler to produce assembly code. Then examine the assembly code to find out the answer.


As James says, code generation is not part of the language standard, so there's no answer within the context of the language.

Practically, though, and especially if you have any sort of optimization, it is entirely possible and to be expected that variables with automatic storage don't actually cause any assembly output at all, for numerous reasons - either a value can be inferred by the compiler, or a pointer-like value (like a reference) refers to something within the same scope and the compiler already knows how to access that datum, and so there's no need to make multiple copies of the same address value at the machine level.

Typical examples which would almost certainly not cause additional code to be generated:

int a = 2875;
char * const pa = reinterpret_cast<char*>(&a); // no code
int & ra = a;                                  // no code

double arr[10];
double & rd = arr[5];                          // no code

std::map<int, std::string> m;
const std::string & s = m.find(8)->second;     // ? ... ->
return foo(s);                                 // ... -> probably no code for s


It generates machine code. t will take the effective address of obj. You can set your compiler to generate assembly and check this yourself. On windows, this is what is generated:

lea eax, DWORD PTR _obj$[ebp]
mov DWORD PTR _t$[ebp], eax

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜