MyCustomObject * object=new MyCustomObject();
Assume the object pointer is used by many of my classes, but all of a sudden I want to change the con
Generally it is preferable to change an object’s properties (by calling its methods) rather than deleting it and creating a new one. In particular, you can completely replace the object by assignment, such as:
*object = MyCustomObject(); // Replace object with the result of default constructor.
Instead of the default constructor, you could use an existing instance of the object (e.g., some static object you define for this purpose) or the result of a function that returns the desired object.
However, you can delete an object but retain its space by calling its destructor, and you can create a new object in the same place by using placement new:
#include
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;
}
After calling the destructor and the placement new, pointers to the old object point to the new object, since it is in the same place the old object was.