gpt4 book ai didi

C++:如何对 scoped_ptr 进行单元测试?

转载 作者:行者123 更新时间:2023-11-30 04:48:49 24 4
gpt4 key购买 nike

假设我实现了一个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 来验证这一点,因为它指向的内存应该有已经被释放了。那我该如何测试呢?

最佳答案

使用带有对象计数的类怎么样?旁注:您需要在 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;
}

关于C++:如何对 scoped_ptr 进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55676120/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com