c++ - initialization of 'unused' is skipped by 'goto label' - why do I get it for std::string but not for int? -
i bumped against error in code, , after experimenting stumbled upon weirdness - std::string
, not int
.
for std::string
error c2362: initialization of 'unused' skipped 'goto label'
:
{ goto label; std::string unused; label:; }
for int
i don't error, however:
{ goto label; int unused = 10; label:; }
why difference? because std::string
has non-trivial destructor?
this covered in draft c++ standard section 6.7
declaration statement says (emphasis mine):
it possible transfer block, not in way bypasses declarations initialization. a program jumps87 point variable automatic storage duration not in scope point in scope ill-formed unless variable has scalar type, class type trivial default constructor , trivial destructor, cv-qualified version of 1 of these types, or array of 1 of preceding types , declared without initializer (8.5).
and provides following example:
void f() { // ... goto lx; // ill-formed: jump scope of ly: x = 1; // ... lx: goto ly; // ok, jump implies destructor // call followed construction // again following label ly }
although both cases should generate error since bypassing initialization in both cases, have been fine:
goto label; int unused ; label:
so visual studio
not correct here, both gcc
, clang
generate , error code, gcc
says:
error: crosses initialization of 'int unused' int unused = 10; ^
of course visual studio
can have extension long document not portable use such extension, pointed out both clang
, gcc
generate error this.
we can find rationale why don't want jump across initialization in defect report 467 sought have same restriction added local static variable (it rejected):
[...]automatic variables, if not explicitly initialized, can have indeterminate (“garbage”) values, including trap representations, [...]
Comments
Post a Comment