What are the dangers of forward declarations?

前端 未结 9 1550
轻奢々
轻奢々 2021-02-01 16:58

I just had an interview. I was asked what is a \"forward declaration\". I was then asked if they were dangers associated with forward declarations.

I could not answer to

9条回答
  •  旧巷少年郎
    2021-02-01 17:15

    Well, apart from the issues about duplication...

    ... there is at least one sore spot in the Standard.

    If you call delete on a pointer to an incomplete type, you get undefined behavior. In practice, the destructor may not get called.

    We can see that on LiveWorkSpace using the following command and sample:

    // -std=c++11 -Wall -W -pedantic -O2
    
    #include 
    
    struct ForwardDeclared;
    
    void throw_away(ForwardDeclared* fd) {
       delete fd;
    }
    
    struct ForwardDeclared {
       ~ForwardDeclared() {
          std::cout << "Hello, World!\n";
       }
    };
    
    int main() {
       ForwardDeclared* fd = new ForwardDeclared();
       throw_away(fd);
    }
    

    Diagnosis:

    Compilation finished with warnings:
     source.cpp: In function 'void throw_away(ForwardDeclared*)':
     source.cpp:6:11: warning: possible problem detected in invocation of delete operator: [enabled by default]
     source.cpp:5:6: warning: 'fd' has incomplete type [enabled by default] 
     source.cpp:3:8: warning: forward declaration of 'struct ForwardDeclared' [enabled by default]
     source.cpp:6:11: note: neither the destructor nor the class-specific operator delete will be called, even if they are declared when the class is defined
    

    Don't you want to thank your compiler for warning you ;) ?

提交回复
热议问题