Currently, I am reading the source code of Protocol Buffer
, and I found one weird enum
codes defined here
~scoped_ptr() { enum { type_must_be_complete = sizeof(C) }; delete ptr_; } void reset(C* p = NULL) { if (p != ptr_) { enum { type_must_be_complete = sizeof(C) }; delete ptr_; ptr_ = p; } }
Why the enum { type_must_be_complete = sizeof(C) };
is defined here? what is it used for?
This trick avoids UB by ensuring that definition of C is available when this destructor is compiled. Otherwise the compilation would fail as the sizeof
incomplete type (forward declared types) can not be determined but the pointers can be used.
In compiled binary, this code would be optimized out and would have no effect.
Note that: Deleting incomplete type may be undefined behavior from 5.3.5/5:.
if the object being deleted has incomplete class type at the point of deletion and the complete class has a non-trivial destructor or a deallocation function, the behavior is undefined.
g++
even issues the following warning:
warning: possible problem detected in invocation of delete operator:
warning: 'p' has incomplete type
warning: forward declaration of 'struct C'
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