0

可能重复:
如何安全地删除多个指针

如下代码:

#include <iostream>
using namespace std;

int main(int argc, _TCHAR* argv[])
{
    int *p, *q;
    q = new int;
    p = q;
    delete q;
    q = NULL;
    cout << p << "  " <<q << endl;
    return 0;
}

p指向q. 当我删除qq=NULL时,p仍然指向旧地址。有没有人有任何方法可以自动p指出q NULL?因为如果在一个程序中有很多指针指向同一个地址,我们不能让它们指向NULL它会带来问题。

4

2 回答 2

4

有一种智能指针可以完成这项工作。这段代码可能存在线程安全问题,(事实上我保证会有)。

template <class T>
class DoublyLinkedSmartPointer
{
   public:
      DoublyLinkedSmartPointer(const DoublyLinkedSmartPointer &other);
      DoublyLinkedSmartPointer& operator=(const DoublyLinkedSmartPointer& other);
      virtual ~DoubleLinkedSmartPointer();
      T * operator*();
      const T* operator*() const;

      void freeAll();
   private:

      DoublyLinkedSmartPointer *next, *previous;
      T * data;
}

基本思想是,每当复制智能指针时,使用用于初始化它的智能指针将副本添加到列表中。当您删除指针时,您将其从列表中释放。

现在,棘手的一点是,由于每个指针都知道其他指针,因此您可以从任意点逐步遍历列表,并将每个节点中的数据设置为 NULL。

好的,这就是你可以做到的。但更重要的是,不要这样做。您几乎肯定会创建难以维护且几乎无法调试的代码。最好的内存管理策略是最简单的。

于 2012-09-29T00:56:53.157 回答
1

The general advise for C++ programs is to avoid elementary pointers, precisely to avoid the issues you're having. Instead, use the language's (or more precisely its standard library's) methods to deal with pointers:

1 use containers, such as std::vector, instead of pointers to (chunks of) memory allocated on the heap

2 use std::unique_ptr and std::shared_ptr (and std::weak_ptr) to manage objects allocated on the heap. This only works properly in C++11 with its move semantics, see the standard header .

advantages: automatic de-allocation without leaving dangling pointers; exception safety (throwing an exception and stack-rewinding does not leak memory).

于 2012-09-29T09:59:31.730 回答