/*
当我们在使用string* str = new string;的时候,
编译器实际上给我们做的是调用::operator new(size_t szie)
其中size是sizeof(string)
而如果你用string* str = new(sizeof(string)) string;
则会出错,也就是说这里的size_t参数是编译器自动给我们加上的,不需要我们自己写;
当我们在使用string* str = new string("xiaolixi");的时候,
先调用operator new 在调用string(char*)的,构造函数的参数不通过
operator new 传入。
*/
#include <iostream>
using namespace std;
class NewOverload{
public:
static void* operator new(size_t size,size_t s){
cout << size <<ends<<s<< endl;
return ::operator new(size);
}
static void operator delete(void* raw,size_t size){
return ::operator delete(raw);
}
NewOverload(int x,int y):m_x(x),m_y(y){
cout << m_x << ends << m_y << endl;
}
~NewOverload(){}
private:
int m_x;
int m_y;
};
int main(){
NewOverload* p = new(sizeof(NewOverload)) NewOverload(1, 2);
return 0;
}
new string("xiaolixi")的参数问题
最新推荐文章于 2022-12-16 21:20:24 发布