mercredi 14 septembre 2016

Why isn't new implemented with template?

I am trying to instrument new with some additional information in order to track down a memory leak. I know, I can override a new operator globally, but I was surprise to discover that I cannot retrieve any information regarding the type of the object being allocated (Correct me if I am wrong). Clearly, it would be beneficial to have the type information when you decide to override the new operator.

For example, I've implemented a simple and generic version of new and delete using variadic template.

std::string to_readable_name(const char * str)
{
    int status;
    char *demangled_name = abi::__cxa_demangle(str, NULL, NULL, &status);
    if(status == 0) {
        std::string name(demangled_name);
        std::free(demangled_name);
        return name;
    }
    return "Unknown";
}

template <typename T, typename... Args>
T * generic_new(Args&&... args) throw (std::bad_alloc)
{
    const std::size_t size = sizeof(T);
    std::cout << "Allocating " << size << " bytes for " << to_readable_name(typeid(T).name()) << std::endl;
    return new T(std::forward<Args>(args)...);
};

template<typename T>
void generic_delete(T* ptr)
{
    const std::size_t size = sizeof(T);
    std::cout << "Deleting " << size << " bytes for " << to_readable_name(typeid(T).name()) << std::endl;
    delete ptr;
}

int main()
{
    auto i = generic_new<int>(0);
    std::cout << *i << std::endl;
    generic_delete(i);

    return 0;
}

My question is why hasn't new be implemented with template? This would allow developer to have information about the type of the object being allocated.

Thank you

Aucun commentaire:

Enregistrer un commentaire