gpt4 book ai didi

c++ - 放置新运算符是否会禁用默认的新运算符?

转载 作者:行者123 更新时间:2023-12-01 14:43:54 25 4
gpt4 key购买 nike

我有一个这样的代码片段

#include <cstring>
#define DISABLE_DEFAULT_NEW \
void* operator new(size_t aSize, void* aPtr); \
void operator delete(void* aPtr);

class A
{
public:
DISABLE_DEFAULT_NEW
A() {}
};

int
main()
{

A* a = new A();
return 0;
}

当我编译它时,我看到这样的错误消息
disable_new.cpp:17:10: error: no matching function for call to 'operator new'
A* a = new A();
^
disable_new.cpp:9:3: note: candidate function not viable: requires 2 arguments, but 1 was provided
DISABLE_DEFAULT_NEW
^
disable_new.cpp:3:9: note: expanded from macro 'DISABLE_DEFAULT_NEW'
void* operator new(size_t aSize, void* aPtr); \
^
1 error generated.

我的问题是默认的新运算符在哪里?我希望new的默认语法仍然有效,规范中是否提到了行为?

最佳答案

他们只是隐藏全局的。如果在类范围内提供 operator new

(强调我的)

The new expression looks for appropriate allocation function's name firstly in the class scope, and after that in the global scope. Note, that as per name lookup rules, any allocation functions declared in class scope hides all global allocation functions for the new-expressions that attempt to allocate objects of this class.



这意味着,如果您在类中定义任何 operator new,则也必须在类中定义其他必要的形式,例如
class A
{
public:
DISABLE_DEFAULT_NEW
A() {}
void* operator new ( std::size_t count ) { return ::operator new(count); } // forward to global operator new
};

关于c++ - 放置新运算符是否会禁用默认的新运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59271597/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com