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 the second question. A search on the net didn't show up any interesting result.
So, do someone know any dangers associated with the use of forward declarations ?
The Google style guide recommends against using forward declarations, and for good reasons: If someone forward declares something from namespace std, then your code exhibits undefined behavior (but will likely work).
Forward declarations in C++ are useful to save in compile time as the compiler does not need to check for translation units in the included header. Also it has other benefits such as preventing namespace pollution, allowing to use PImpl idiom and it may even reduce the binary size in some cases.
By asking it so specifically in the negative you are preventing people from giving the best answers to the question: you should forward declare by default and avoid it only in rare situations. There are reasons not to but they're not sufficient to recommend against.
Forward declaration is used in languages that require declaration before use; it is necessary for mutual recursion in such languages, as it is impossible to define such functions (or data structures) without a forward reference in one definition: one of the functions (respectively, data structures) must be defined ...
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 ;) ?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With