MyCustomObject * object=new MyCustomObject();
Run Code Online (Sandbox Code Playgroud)
假设我的许多类都使用了对象指针,但突然间我想改变指针的内容而不改变地址.
我错误地认为object = new MyCustomObject()会给对象一个新的指针地址吗?我想要新对象而不更改指针地址(是的,我将确保清理旧对象).
考虑以下代码,
#include "iostream"
#include "conio.h"
using namespace std;
class sample
{
private:
int i;
public:
sample(int ii=0) : i(ii){
cout<<"Constructing Object"<<endl;
}
~sample() { cout<<"Destructing Object"<<endl; }
void* operator new(size_t nSize, void* loc){
cout <<"Inside new"<<endl;
cout <<loc<<endl;
return loc;
}
void operator delete(void* ptr){
cout <<"Inside delete"<<endl;
free(ptr);
}
};
int main()
{
int intArr[2];
sample* samplePtr = new(intArr) sample(5);
cout <<samplePtr<<endl;
delete samplePtr;
// samplePtr->sample::~sample();
getch();
}
Run Code Online (Sandbox Code Playgroud)
输出:
Inside New
0x22ff38
Constructing Object
0x22ff38
Destructing Object
Inside Delete …Run Code Online (Sandbox Code Playgroud)