Why does C++ enforce such behavior in crosses initialization? [duplicate]

天涯浪子 提交于 2019-12-12 08:22:07

问题


Let's say I have some c++ code:

if (error)
    goto exit;
... 
// size_t i = 0; //error
size_t i;
i = 0;
...
exit:
    ...

I understand we should not use goto, but still why does

size_t i;
i = 0;

compile whereas size_t i = 0; doesn't?

Why is such behavior enforced by the standard (mentioned by @SingerOfTheFall)?

It is possible to transfer into a block, but not in a way that bypasses declarations with initialization. A program that jumps from a point where a local variable with automatic storage duration is not in scope to a point where it is in scope is ill-formed unless the variable has POD type (3.9) and is declared without an initializer.


回答1:


You can't jump over initialization of an object.

size_t i = 0; 

is an initialization, while

size_t i;
i = 0;

is not. The C++ Standart says:

It is possible to transfer into a block, but not in a way that bypasses declarations with initialization. A program that jumps from a point where a local variable with automatic storage duration is not in scope to a point where it is in scope is ill-formed unless the variable has POD type (3.9) and is declared without an initializer.




回答2:


The reason for the rule is that jumping over an initialization leaves the object in an undefined state. When you get to the end of the function, destroying those uninitialized objects might not work.

One exception is obviously that

int   i;

leaves the int uninitialized anyway, so skipping that is just half bad.

If you want to leave a function early, a quick return is an option to avoid the goto.



来源:https://stackoverflow.com/questions/11306799/why-does-c-enforce-such-behavior-in-crosses-initialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!