放置新运算符是否禁用默认的新运算符?
Does placement new operator disable the default new operator?
我有一个这样的代码片段
#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 的默认语法仍然有效,规范中的任何地方都提到了它的行为吗?
他们只是隐藏了全局的。如果在 class 范围内提供 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.
也就是说,如果你在class中定义了任何operator new
,你还必须在class中定义其他必要的形式,例如
class A
{
public:
DISABLE_DEFAULT_NEW
A() {}
void* operator new ( std::size_t count ) { return ::operator new(count); } // forward to global operator new
};
我有一个这样的代码片段
#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 的默认语法仍然有效,规范中的任何地方都提到了它的行为吗?
他们只是隐藏了全局的。如果在 class 范围内提供 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.
也就是说,如果你在class中定义了任何operator new
,你还必须在class中定义其他必要的形式,例如
class A
{
public:
DISABLE_DEFAULT_NEW
A() {}
void* operator new ( std::size_t count ) { return ::operator new(count); } // forward to global operator new
};