Search code examples
c++new-operator

Why can't use placement new if I overrride operator new?


I think there may be an exsiting implemented void* operator new(std::size_t, void*) for it. Is this true?

gcc version 8.1.0

#include<iostream>
#include <new>

class Base {
public:
    char c = 'a';
    int i = 42;

    // can't use placement new if this function exists
    void* operator new(std::size_t size) {
        std::cout << "Base::new()" << std::endl;
        std::cout << "param size: " << size << std::endl; // 8. actual size of Base instance
        return malloc(size);
    }
};



int main()
{
    char buff[100];
    Base* b1 = new Base;
    Base* b2 = new ((void*)buff) Base; // error: no matching function for call to 'Base::operator new(sizetype, void*)'
    std::cout << buff[0] << std::endl; // a
    std::cout << *((int*)&buff[4]) << std::endl; // 42

    delete b1;
    b2->~Base();
    return 0;
}

I searched on the Internet and asked ChatGPT, both got nothing.


Solution

  • To avoid (I believe) selecting the wrong overload of new, you need to do:

    Base* b2 = ::new ((void*) buff) Base;
    

    Also, if you provide your own operator new, you need to provide a corresponding implementation for operator delete (not done in my example):

    https://wandbox.org/permlink/eMrZxd7epzF6KHUk

    Output:

    Base::new()
    param size: 8
    42