c++ - 关于这个智能指针类

标签 c++

我在书上看到这段代码,一个简单的智能指针,有几个问题:

    template <class T>
class SmartPointer {
 public:
    SmartPointer(T * ptr) {
        ref = ptr;
        ref_count = malloc(sizeof(unsigned));
        *ref_count = 1;
    }
    SmartPointer(SmartPointer<T> & sptr) {
        ref = sptr.ref;
        ref_count = sptr.ref_count;
        ++*ref_count;
    }
    SmartPointer<T> & operator=(SmartPointer<T> & sptr) {
        if (this != &sptr) {
           ref = sptr.ref;
           ref_count = sptr.ref_count;
           ++*ref_count;
        }
        return *this;
    }
    ~SmartPointer() {
        --*ref_count;
        if (*ref_count == 0) {
           delete ref;
           free(ref_count);
           ref = ref_count = NULL;
        }
    }
    T* operator->() { return ref; }
    T& operator*() { return *ref; }
 protected:
    T * ref;
    unsigned * ref_count; 
};

这是我的问题: 1、ref_count为什么要用malloc初始化?为什么不能是 ref_count = new unsigned(); 2.=运算符函数,它不需要清理旧值吗?此代码似乎会导致引用计数错误。

谢谢,

最佳答案

你这本书是垃圾。你需要把它扔掉。此代码甚至无法编译。

  1. malloc 并不比 new unsigned(1) 好多少。 malloc() 返回需要转换为 unsigned*void* ,显然这里没有这样做。
  2. 你是对的,需要注意之前指向的对象的引用计数。

为什么不尝试研究 boost::shared_ptrstd::shared_ptr 的实现?无论如何,您很可能最终会使用它。

关于c++ - 关于这个智能指针类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12170772/

相关文章:

C++ 单例/事件对象范例

c++ - 来自 boost/serialization/vector #include 的链接器错误

string - find_if 在字符串数组上

c++ - 给指针指向的地址赋值? C++

android - 如何将 OpenCV 集成到 Qt Creator Android 项目中

c++ - 如何使用 Boost 和 C++ 递归地单独列出文件和文件夹

c++ - 了解 C++ 内存模型 : Different values on different runs

c++ - 函数如何返回指向带有函数的函数的指针?

c++ - 使用 memcpy 填充后删除动态二维数组时中止(核心转储)

c++ - 使用 "Length"的头文件的 For 循环中出现错误 C867