为什么如果我覆盖了operator new就不能使用placement new了?

问题描述 投票:0回答:1

我认为可能已经有一个已实施的

void* operator new(std::size_t, void*)
。 这是真的吗?

海湾合作委员会版本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;
}

我在网上搜索并询问ChatGPT,都没有得到。

c++ new-operator
1个回答
0
投票

为了避免(我相信)选择错误的

new
重载,你需要这样做:

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

另外,如果您提供自己的

operator new
,则需要为
operator delete
提供相应的实现(在我的示例中未完成):

https://wandbox.org/permlink/eMrZxd7epzF6KHUk

输出:

Base::new()
param size: 8
42
© www.soinside.com 2019 - 2024. All rights reserved.