1

the following code used to delete a singleton instance, why the works before delete is necessary?

// @brief Destruct the singleton instance
// @note Only work with gcc/clang
__attribute__((destructor)) static void delete_() {
    //works before delete
    typedef char T_must_be_complete[sizeof(T) == 0 ? -1 : 1];
    (void) sizeof(T_must_be_complete);
    delete instance_;
}

1 Answers1

1

This is a delete that first checks whether the type is complete. Similar to boost::checked_delete.

The idea of it is to generate a compilation error when attempting to delete an incomplete type (which has a good chance of causing undefined behavior, depending on the type).

For example (using boost::checked_delete for convenience, since I don't know the specifics of the class of which your delete_ is a member, but they're basically the same) :

struct X;

void foo(X* x) {
    boost::checked_delete(x);
}

Note that a regular delete x; might cause a warning from the compiler (depending on your compiler), but that's not guaranteed.

Sander De Dycker
  • 16,053
  • 1
  • 35
  • 40
  • I wonder why a simple `(void)sizeof(T);` didn't cut it -- are there versions of GCC or Clang that will return `0` for an incomplete type? – Quentin Oct 10 '19 at 09:43
  • 1
    @Quentin : I can't speak for the OP's code, but for `boost::checked_delete` which is very similar, the complexity was added to cover for a CodeWarrior 8 bug : [commit](https://github.com/boostorg/core/commit/e6d3d3dbb188bd5d6aac6e97c7609efa3494e282#diff-bf75d3e38756c220413f469204c9864e), [mailing list](https://lists.boost.org/Archives/boost/2003/08/51558.php) – Sander De Dycker Oct 10 '19 at 10:01
  • 1
    oh, and the Intel 7 compiler : [commit](https://github.com/boostorg/core/commit/82aa7bfcbc140a8dbfdc2c86643df1977ccdb17c), [mailing list](https://lists.boost.org/Archives/boost/2003/07/49958.php) – Sander De Dycker Oct 10 '19 at 10:26