What are the dangers of forward declarations?

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 <iostream>

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 😉 ?

Leave a Comment

techhipbettruvabetnorabahisbahis forumu