C++ new and delete

Source:

https://kelvinh.github.io/blog/2014/04/19/research-on-operator-new-and-delete/

What do new and delete code mean

Class *pc = new Class;
// ...
delete pc;

The first line above is the new operator, and the third line is the delete operator. The code is simple, but for the compiler, it needs to do additional work, translating the above code into something approximate to the following code:

void *p = operator new(sizeof(Class));
// Call the constructor of Class on the memory pointed to by p, this can't be shown with straightforward code
Class *pc = static_cast<Class*>(p);
// ...
pc->~Class();
operator delete(pc);

What does the operator new actually do, and what does the operator delete do?

void * operator new(std::size_t size) throw(std::bad_alloc) {
    if (size == 0)
        size = 1;
    void* p;
    while ((p = ::malloc(size)) == 0) {
        std::new_handler nh = std::get_new_handler();
        if (nh)
            nh();
        else
            throw std::bad_alloc();
    }
    return p;
}

void operator delete(void* ptr) {
    if (ptr)
        ::free(ptr);
}

It’s actually a wrapper for malloc, but it allocates at least one byte, and in case of memory failure, it attempts to get the user-set new_handler. If the user has previously set a new_handler, then it will call the new_handler; otherwise, it will throw a bad_alloc exception.

What is placement new

inline _LIBCPP_INLINE_VISIBILITY void* operator new  (std::size_t, void* __p) _NOEXCEPT {return __p;}

This is an overload of operator new. It directly returns the value of the pointer. It seems quite useless. So how is it used?

void *buf = // Allocate memory for buf here
Class *pc = new (buf) Class();

The above code assigns buf’s memory to the pc pointer. It’s actually equivalent to:

((* Class)buf)->Class();
Class *pc = buf;
comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy