【发布时间】:2018-04-23 11:20:55
【问题描述】:
下面是vs2015下运行的一段代码sn-p:
#include<iostream>
using namespace std;
class A {
public:
A(int _a,int _b){}
//func1
void* operator new(size_t sz) {
cout << "func1"<<endl;
return malloc(sz);
}
};
//func2
void* operator new(size_t sz) {
cout << "func2" << endl;
return malloc(sz);
}
int main() {
int* i = new int;//OK,it calls the func2
int* i1 = new int[6];//why does it call the func2,not the implicit default `operator new[]`?
A *a = new A(1, 2);//OK,it calls the func1
A* a1 = new A[2]{ {1,2},{3,4} };//why does it call the func2 instead of func1?
return 0;
}
问题:
我们知道,如果我们想改变
new[]的行为,我们只需要定义和替换默认的operator new[]。但是,为什么重载operator new也会改变它的行为? 标准是否定义或要求这种行为实现?有什么方法可以阻止这种行为,因为我只想要new[]的默认行为?基于问题1,如果重载
operator new会改变new[]的行为,为什么new A[2]语句中没有调用func1,而是func2?
补充:
来自another code snippet,cppref cmets int* p2 = new int[10]; // guaranteed to call the replacement in C++11. 似乎第一次在 C++11 标准中保证了这种行为。
【问题讨论】:
-
IIRC在全局范围内,
::new[]是从::new定义的,所以... -
是的,查看en.cppreference.com/w/cpp/memory/new/operator_new 中的条目(2):“标准库实现调用版本(1)”
-
@YSC 那么它的实现是标准定义的还是要求的?
-
我猜是前者。
-
@YSC 来自linkage 中的一个代码 sn-p,cppref cmets
int* p2 = new int[10]; // guaranteed to call the replacement in C++11。从标准 c++11 开始,这种行为似乎得到了保证。
标签: c++ operator-overloading language-lawyer new-operator