Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird enum in destructor

Tags:

c++

enums

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?

like image 919
zangw Avatar asked Nov 19 '15 10:11

zangw


1 Answers

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'

like image 135
Mohit Jain Avatar answered Oct 02 '22 06:10

Mohit Jain