1

假设我已经实现了scoped_ptr

template <typename T> class scoped_ptr {
 public:
  scoped_ptr() = delete;
  explicit scoped_ptr(T *ptr) : _ptr(ptr){};
  ~scoped_ptr() {
    delete _ptr;
    _ptr = nullptr;
  };

  scoped_ptr(const scoped_ptr &p) = delete;
  scoped_ptr &operator=(const scoped_ptr &p) = delete;

  T *operator->() const { return _ptr; }
  T &operator*() const { return *_ptr; }
  T *get() const { return _ptr; }
  void reset(T *p = nullptr) {
    delete _ptr;
    _ptr = p;
  }

 private:
  T *_ptr;
};

我想测试在指针的生命周期结束后内存实际上是否被释放,但我无法通过取消引用该原始指针来验证这一点,_ptr因为预计它指向的内存应该已经被释放。那我该如何测试呢?

4

1 回答 1

1

使用具有对象计数的类怎么样?旁注:您需要检查reset.

演示:https ://ideone.com/hnxc9o 。

#include <cassert>
#include <iostream>

using namespace std;

template <typename T>
class scoped_ptr {
 public:
  scoped_ptr() = delete;
  explicit scoped_ptr(T *ptr) : _ptr(ptr) {}
  virtual ~scoped_ptr() { reset(); }

  scoped_ptr(const scoped_ptr &p) = delete;
  scoped_ptr &operator=(const scoped_ptr &p) = delete;

  T* operator->() const { return _ptr; }
  T& operator*() const { return *_ptr; }
  T* get() const { return _ptr; }
  void reset(T* p = nullptr) {
    if (_ptr == p) {
      return;
    }
    delete _ptr;
    _ptr = p;
  }

 private:
  T* _ptr;
};

struct ObjectCounter {
  static int _object_count;
  ObjectCounter() {
    ++_object_count;
  }
  virtual ~ObjectCounter() {
    --_object_count;
  }
};

int ObjectCounter::_object_count = 0;

int main() {
  {
    scoped_ptr<ObjectCounter> ptr(new ObjectCounter());
    assert(ObjectCounter::_object_count == 1);
  }
  assert(ObjectCounter::_object_count == 0);
  return 0;
}
于 2019-04-15T06:31:40.690 回答