mardi 20 février 2018

Is pointer pointing to a single element or to an array?

I'm coding up a cleanup utility that will store items to be cleaned up in a tuple and in case of an error condition will do appropriate action for each item in the tuple. Some of the typical items in the tuple would be pointers to objects that were allocated on the heap. When my cleanup handler decides to delete these objects, it must know whether it should use the vanilla delete expression or the array form of delete expression (delete[]). How would I go about determining whether an item in the tuple is a pointer to a single object or a pointer to an array of objects.

Here is a sample implementation. And here are the sections that are relevant to this question:

template<unsigned index, typename... Types>
struct TupleItemDeleter
{
    void operator() (std::tuple<Types...>& t)
    {
        std::cout << "Deleting item at index " << index << std::endl;
        delete std::get<index>(t); //HOWTO: delete[] or delete?
        TupleItemDeleter<index - 1, Types...>{}(t);
    }
};

template<typename... Types>
struct TupleItemDeleter<0, Types...> 
{
    void operator() (std::tuple<Types...>& t)
    {
        std::cout << "Deleting item at index 0" << std::endl;
        delete std::get<0>(t); //HOWTO: delete[] or delete?
    }
};

template<typename... Types>
void deleter(std::tuple<Types...>& t)
{
    constexpr auto tupleSize = std::tuple_size<std::tuple<Types...>>::value;
    TupleItemDeleter<tupleSize - 1, Types...>{}(t);
}

PS: I tried std::is_array, it's not helpful in my case.

Aucun commentaire:

Enregistrer un commentaire