C++:如何对 scoped_ptr 进行单元测试?
C++: How to unit test a scoped_ptr?
假设我实现了一个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
因为它指向的内存应该已经被释放了被释放。那我要怎么测试呢?
使用带有对象计数的 class 怎么样?旁注:您需要检查 reset
.
中的自赋值
#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;
}
假设我实现了一个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
因为它指向的内存应该已经被释放了被释放。那我要怎么测试呢?
使用带有对象计数的 class 怎么样?旁注:您需要检查 reset
.
#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;
}