c++ - 如何开始编写智能指针?

标签 c++ pointers smart-pointers

我在大学刚接到一个任务,就是写一个智能指针。我收到了一个骨架,我需要实现所需的方法。如果我是对的,智能指针是一种指针,它计算给定对象的引用号(?),如果该计数器达到零,它会删除给定的对象。

这是骨架:

template<class T>
class my_pointer {
public:       
    my_pointer();
};

class refcounted {
    /* the reference counted types should have the public interface that is defined here */
public:     
    int incRefCnt();
    int decRefCnt();
};

int main() {
    my_pointer<refcounted> obj1 = new refcounted();
    my_pointer<refcounted> obj2 = obj1;

    return 0;
}

首先,这条线应该做什么? refcounted 不是 my_pointer 的子对象,所以我怎么可能实例化一个新的 refcounted 对象并用 my_pointer 对象(指针?)引用它?

my_pointer<refcounted> obj1 = new refcounted();

为什么my_pointer类中没有计数器,而refcounted类中有计数器?我应该如何开始呢?我不太擅长c++。提前致谢!

最佳答案

Firstly, what should this line do?

my_pointer<refcounted> obj1 = new refcounted();

该行应该初始化一个 my_pointer<refcounted>来自 refcounted 的智能指针传递给它的原始指针。

how can I possibly instantiate a new refcounted object and reference it with a my_pointer object (pointer?)?

您可以使用 converting constructor 来做到这一点. my_pointer没有接受 T* 的构造函数, 所以它似乎留给你来定义。

Why isn't there a counter in the my_pointer class, and why is the counter in the refcounted class?

显然,您的任务是创建一个侵入式指针,该指针期望存储的对象进行引用计数。

How should I start with this?

我会看一眼boost::intrusive_ptr的描述和界面.不过,您的作业可能不需要那么完整的界面。

关于c++ - 如何开始编写智能指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33445426/

相关文章:

c++ - 缓存刷新例程之间的时间不一致

c++ - std::string 到 SecByteBlock 的转换

python - 如何将双指针 c 类型转换为 numpy 数组?

c# - float* 从 C 到 C#

c++ - 如何正确地将所有权从原始指针移动到 std::unique_ptr?

c++ - decltype 规则定义左值或纯右值

c++ - Windows C++组播发送

c - 在 C : swapping pointers leads to unexpected results 中排序

c++ - 哈夫曼压缩器/解压器

c++ - 将 weak_ptr 与 unique_ptr 配对是个好主意吗?