Compiler stops optimizing unused string away when adding characters

前端 未结 3 1959
日久生厌
日久生厌 2020-12-23 18:49

I am curious why the following piece of code:

#include 
int main()
{
    std::string a = \"ABCDEFGHIJKLMNO\";
}

when compiled

3条回答
  •  长情又很酷
    2020-12-23 19:25

    While the accepted answer is valid, since C++14 it's actually the case that new and delete calls can be optimized away. See this arcane wording on cppreference:

    New-expressions are allowed to elide ... allocations made through replaceable allocation functions. In case of elision, the storage may be provided by the compiler without making the call to an allocation function (this also permits optimizing out unused new-expression).

    ...

    Note that this optimization is only permitted when new-expressions are used, not any other methods to call a replaceable allocation function: delete[] new int[10]; can be optimized out, but operator delete(operator new(10)); cannot.

    This actually allows compilers to completely drop your local std::string even if it's very long. In fact - clang++ with libc++ already does this (GodBolt), since libc++ uses built-ins __new and __delete in its implementation of std::string - that's "storage provided by the compiler". Thus, we get:

    main():
            xor eax, eax
            ret
    

    with basically any-length unused string.

    GCC doesn't do but I've recently opened bug reports about this; see this SO answer for links.

提交回复
热议问题