c++templatesc++11g++g++-4.7

How to invoke descructor of static array in C++ template?


How can the following template function be implemented in C++11 in order to support array types as a template parameter? Currently compilation fails with the error as below. Is there some syntactic trick that works this around?

template<typename T>
void destroy(T &o) { o.~T(); }

int main()
{
    int x;
    char y[3];
    destroy(x);
    destroy(y);
}

Output:

$ g++ test.cpp
test.cpp: In instantiation of ‘void destroy(T&) [with T = char [3]]’:
test.cpp:9:18:   required from here
test.cpp:2:26: error: request for member ‘~char [3]’ in ‘o’, which is of non-class type ‘char [3]’

Update: if a buffer of wrappers like struct Storage { CharType value; } is used instead of CharType (i.e. Storage* instead of CharType*) then this could allow the destructor of the CharType = array be called via Storage::~Storage(). And this could work in the code that caused this question. However, the question remains: if it is allowed to invoke a destructor of a fixed-size array explicitly in C++ and if it is then how to do this?


Solution

  • Just be a bit more explicit for arrays and don't forget to pass them by reference to avoid array-decay:

    template<typename T>
    void destroy(T &o) { o.~T(); }
    
    template<typename T, size_t N>
    void destroy(T (&o)[N]) {
        for(size_t i = N; i-- > 0;)
            destroy(o[i]);
    }
    

    BTW: Calling the dtor is only supported for type-names. int is not a type-name. So, it's no hardship, because who would want to explicitly destruct an explicit fundamental type anyway?