Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for Complete type

I came across this code in boost/checked_delete.hpp

Can somebody explain what are line#1 and line#2 doing?

template<class T> inline void checked_array_delete(T * x)
{
    typedef char type_must_be_complete[ sizeof(T)? 1: -1 ];     #1 
    (void) sizeof(type_must_be_complete);                       #2
    delete [] x;
}

From this page, I got this info regarding their purpose,

T must be a complete type. The expression delete [] p must be well-formed.

but, what is a complete type in C++?

like image 808
Saurav Sahu Avatar asked Oct 17 '25 08:10

Saurav Sahu


1 Answers

To answer that, one needs to answer what is an incomplete type. The standard actually has a definition ([basic.types]/5):

A class that has been declared but not defined, an enumeration type in certain contexts ([dcl.enum]), or an array of unknown bound or of incomplete element type, is an incompletely-defined object type. Incompletely-defined object types and cv void are incomplete types ([basic.fundamental]). Objects shall not be defined to have an incomplete type.

The "certain contexts" refers to situations when there isn't a complete definition of the type yet. For instance, a forward declaration of an enum enum foo : int; declares an incomplete type.

Now, since sizeof may not be applied to incomplete types ([expr.sizeof]/1):

The sizeof operator shall not be applied to an expression that has function or incomplete type, to the parenthesized name of such types, or to a glvalue that designates a bit-field.

That typedef is ill-formed for any type the standard lists in the first quoted paragraph. And you'll get an error message that includes the text type_must_be_complete.

And just in case there is some pathological compiler extension that allows a type to have 0 size, the author is being cautious and making sure the array definition is still ill-formed, by giving it a negative size. So you won't be calling delete[] in those pathological case either.

like image 71
StoryTeller - Unslander Monica Avatar answered Oct 19 '25 00:10

StoryTeller - Unslander Monica