C++ 指针 : changing the contents without changing the address?

标签 c++ pointers

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/

相关文章:

c++ - 如何在谷歌测试中强制正确的预期和实际顺序?

c++ - 此素数测试函数的时间复杂度

c++ - (Re)named std::pair 成员中断初始化

c - 在C中初始化库外.lib的函数指针

C 在数组中存储变量的地址

c++ - 返回并使用指向另一个类的多维数组的指针

c++ - 无法理解赋值运算符的重载

C++避免代码重复运算符重载

c++ - 坚持定义静态指针并使用它

c++ - 试图为成员(member)回拨