Why doesn't GCC optimize out deletion of null pointers in C++?

后端 未结 6 1168
情歌与酒
情歌与酒 2021-02-02 05:54

Consider a simple program:

int main() {
  int* ptr = nullptr;
  delete ptr;
}

With GCC (7.2), there is a call instruction regardi

6条回答
  •  野的像风
    2021-02-02 06:43

    First of all, I'll just agree with some previous answerers in that it's not a bug, and GCC may do as it pleases here. That said, I was wondering whether this means that some common and simple RAII code may be slower on GCC than Clang because a straightforward optimization is not done.

    So I wrote a small test case for RAII:

    struct A
    {
        explicit A() : ptr(nullptr) {}
        A(A &&from)
            : ptr(from.ptr)
        {
            from.ptr = nullptr;
        }
    
        A &operator =(A &&from)
        {
            if ( &from != this )
            {
                delete ptr;
                ptr = from.ptr;
                from.ptr = nullptr;
            }
            return *this;
        }
    
        int *ptr;
    };
    
    A a1;
    
    A getA2();
    
    void setA1()
    {
        a1 = getA2();
    }
    

    As you may see here, GCC does elide the second call to delete in setA1 (for the moved-from temporary that was created in the call to getA2). The first call is necessary for program correctness because a1 or a1.ptr may have been previously assigned to.

    Obviously I would prefer more "rhyme and reason" – why is the optimization done sometimes but not always – but I'm not willing to sprinkle redundant if ( ptr != nullptr ) checks all over my RAII code just yet.

提交回复
热议问题