简体   繁体   中英

C++ const compiler optimization

Say I have the following code:

int foo () {
    int const x = 0;
    return x;
}

Is the compiler allowed to move x to the global scope?

What about in the following scenaro? Can res2 vary depending on opimizations?

std::set<int const *> addrs;

int foo () {
    int const x = 0;
    addrs.insert(&x);
    return addrs.size();
}

void bar () {
    int res1 = foo();
    int res2 = foo();
}

No, the compiler can't move it in global scope, because the variable isn't declared at global scope. Scope isn't the same thing as storage. Scope denotes where the variable can be accessed from - moving it to the global scope would mean that it can be accessed from anywhere, which isn't the case here.

The second part of the program exhibits undefined behavior . addrs contains dangling pointers after the function exits. Because std::set compares the existing pointers on insertion, this is illegal. So I'd say yes, res2 can vary, but because of the UB, not the reason you suspect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM