MyCustomObject * object=new MyCustomObject();
假设我的许多类都使用了对象指针,但突然间我想在不更改地址的情况下更改指针的内容。
我认为 object = new MyCustomObject()
会给对象一个新的指针地址是不是错了?我想要新对象而不更改指针地址(是的,我会确保清理旧对象)。
最佳答案
通常最好更改对象的属性(通过调用其方法)而不是删除它并创建一个新对象。特别是可以完全通过赋值来替换对象,如:
*object = MyCustomObject(); // Replace object with the result of default constructor.
您可以使用对象的现有实例(例如,您为此目的定义的一些静态对象)或返回所需对象的函数的结果,而不是默认构造函数。
但是,您可以通过调用其析构函数来删除对象但保留其空间,并且您可以使用放置 new
在同一位置创建新对象:
#include <iostream>
class MyObject
{
public:
MyObject() { std::cout << "I was created at " << (void *) this << ".\n"; }
~MyObject() { std::cout << "Farewell from " << (void *) this << ".\n"; }
};
int main(void)
{
// Allocate space and create a new object.
MyObject *p = new MyObject;
// Destroy the object but leave the space allocated.
p->~MyObject();
// Create a new object in the same space.
p = new (p) MyObject;
// Delete the object and release the space.
delete p;
return 0;
}
在调用析构函数和放置new
之后,指向旧对象的指针指向新对象,因为它与旧对象在同一个地方。
关于C++ 指针 : changing the contents without changing the address?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16945547/