Can different optimization levels lead to functionally different code?

前端 未结 13 1907
[愿得一人]
[愿得一人] 2020-12-13 12:39

I am curious about the liberties that a compiler has when optimizing. Let\'s limit this question to GCC and C/C++ (any version, any flavour of standard):

Is it possi

13条回答
  •  天命终不由人
    2020-12-13 13:21

    OK, my flagrant play for the bounty, by providing a concrete example. I'll put together the bits from other people's answers and my comments.

    For the purpose of different behaviour at different optimizations levels, "optimization level A" shall denote gcc -O0 (I'm using version 4.3.4, but it doesn't matter much, I think any even vaguely recent version will show the difference I'm after), and "optimization level B" shall denote gcc -O0 -fno-elide-constructors.

    Code is simple:

    #include 
    
    struct Foo {
        ~Foo() { std::cout << "~Foo\n"; }
    };
    
    int main() {
        Foo f = Foo();
    }
    

    Output at optimization level A:

    ~Foo
    

    Output at optimization level B:

    ~Foo
    ~Foo
    

    The code is totally legal, but the output is implementation-dependent because of copy constructor elision, and in particular it's sensitive to gcc's optimization flag that disables copy ctor elision.

    Note that generally speaking, "optimization" refers to compiler transformations that can alter behavior that is undefined, unspecified or implementation-defined, but not behavior that is defined by the standard. So any example that satisfies your criteria necessarily is a program whose output is either unspecified or implementation-defined. In this case it's unspecified by the standard whether copy ctors are elided, I just happen to be lucky that GCC reliably elides them pretty much whenever allowed, but has an option to disable that.

提交回复
热议问题