http://gcc.gnu.org/bugzilla/show_bug.cgi?id=55239



             Bug #: 55239

           Summary: Spurious "unused variable" warning on function-local

                    objects with a destructor and an initializer

    Classification: Unclassified

           Product: gcc

           Version: 4.7.1

            Status: UNCONFIRMED

          Severity: minor

          Priority: P3

         Component: c++

        AssignedTo: unassig...@gcc.gnu.org

        ReportedBy: bisq...@iki.fi





In the code below, a function-local object is declared with a destructor whose

role is to ensure that some action is taken at the end of the scope, no matter

which route the function is exited.



    #include <stdio.h>

    void LoadSomeFile(const char* fn)

    {

        /* Open file */

        FILE* fp = fopen(fn, "rb");

        /* Ensure that the file is automatically closed no matter which path

this function is exited */

        struct closer { FILE* f;  ~closer() { if(f) fclose(f); }

                      } autoclosefp = {fp};

        /* Some code here that deals with fp, and may include several "return;"

clauses */

    }

    int main() { LoadSomeFile(__FILE__); } // test



Bug GCC gives a spurious "unused variable 'autoclosefp'" for this code,

implying that autoclosefp has no function. It does. Without it, the file would

not be closed and resources would be leaked.



The problem also occurs, when the code is rewritten like this:



    #include <stdio.h>

    void LoadSomeFile(const char* fn)

    {

        /* Open file */

        FILE* fp = fopen(fn, "rb");

        /* Ensure that the file is automatically closed no matter which path

this function is exited */

        struct closer { FILE* f;  ~closer() { if(f) fclose(f); } };

        closer autoclosefp = {fp};

        /* Some code here that deals with fp, and may include several "return;"

clauses */

    }

    int main() { LoadSomeFile(__FILE__); } // test



Changing the "= {fp}" into C++11 style "{fp}" does not take away the warning,

either.



Only changing the initialization-by-initializer into an member-assignment takes

away the warning.



    #include <stdio.h>

    void LoadSomeFile(const char* fn)

    {

        /* Open file */

        FILE* fp = fopen(fn, "rb");

        /* Ensure that the file is automatically closed no matter which path

this function is exited */

        struct closer { FILE* f;  ~closer() { if(f) fclose(f); } } autoclosefp;

        autoclosefp.f = fp;

        /* Some code here that deals with fp, and may include several "return;"

clauses */

    }

    int main() { LoadSomeFile(__FILE__); } // test



I would argue that this is inconvenient, and wrong behavior on GCC.



Tested and verified on GCC 3.3 through 4.7.1. The -Wunused-variable (or -Wall)

option is required.

Reply via email to