旧解决方案
另一个赋值运算符呢?
counted_ptr& counted_ptr::operator=(T* p)
{
    if (! --*count) { delete count; }
    pointer = p;
    count = new int(1);
    return *this;
}
...
one = new double(5);
此外,您的析构函数总是删除一个共享指针,这可能是导致 *one 成为随机数的原因。也许你想要类似的东西:
counted_ptr::~counted_ptr() { if (! --*count) { delete pointer; delete count; } }
新解决方案
当您希望重新指向 counted_ptr (例如one = new double(5))以更新所有相关counted_ptr的 s 时,请将指针和计数都放在帮助程序类中,并让您的指针类保存指向帮助程序类的指针(您可能已经走上了这条路)。您可以通过两种方式填写此设计:
- 使辅助类成为一个简单的结构(和一个私有内部类),并将所有逻辑放在外部类方法中
 
制作counted_ptr助手类。counted_ptr维护一个引用计数,但不会自动更新计数;它不是智能指针,它只响应release和retain消息。如果您完全熟悉 Objective-C,这基本上就是它的传统内存管理(除了自动释放)。counted_ptr当引用计数达到 0(与 Obj-C 的另一个潜在差异)时,可能会或可能不会删除自身。counted_ptrs 不应该是可复制的。目的是对于任何普通指针,最多应该有一个counted_ptr.
创建一个smart_ptr具有指向 a 的指针的类,该指针在应该持有相同普通指针的实例counted_ptr之间共享。负责通过发送其释放和保留方法自动更新计数。smart_ptrsmart_ptrcounted_ptr
counted_ptr可能是也可能不是shared_ptr.
 
这是选项二的界面。由于您将其作为练习进行,因此我将让您填写方法定义。潜在的实现将类似于已经发布的内容,只是您不需要复制构造函数和复制赋值运算符 for counted_ptr,counted_ptr::~counted_ptr不调用counted_ptr::release(这是smart_ptr::~smart_ptr的工作)并且counted_ptr::release可能无法释放counted_ptr::_pointer(您可能会将其留给析构函数) .
// counted_ptr owns its pointer an will free it when appropriate.
template <typename T>
class counted_ptr {
private:
    T *_pointer;
    size_t _count;
    // Make copying illegal
    explicit counted_ptr(const counted_ptr&);
    counted_ptr& operator=(const counted_ptr<T>& p);
public:
    counted_ptr(T* p=0, size_t c=1);
    ~counted_ptr();
    void retain();        // increase reference count.
    bool release();       // decrease reference count. Return true iff count is 0
    void reassign(T *p);  // point to something else.
    size_t count() const;
    counted_ptr& operator=(T* p);
    T& operator*() const;
    T* operator->() const;
};
template <typename T>
class smart_ptr {
private:
    counted_ptr<T> *_shared;
    void release();  // release the shared pointer
    void retain();   // retain the shared pointer
public:
    smart_ptr(T* p=0, int c=1);   // make a smart_ptr that points to p
    explicit smart_ptr(counted_ptr<T>& p); // make a smart_ptr that shares p
    explicit smart_ptr(smart_ptr& p); // copy constructor
    ~smart_ptr();
    // note: a smart_ptr's brethren are the smart_ptrs that share a counted_ptr.
    smart_ptr& operator=(smart_ptr& p); /* Join p's brethren. Doesn't alter pre-call
        * brethren. p is non-const because this->_shared can't be const. */
    smart_ptr& operator=(counted_ptr<T>& p);  /* Share p. Doesn't alter brethren. 
        * p is non-const because *this isn't const. */
    smart_ptr& operator=(T* p); // repoint this pointer. Alters brethren
    size_t count() const; // reference count
    T& operator*() const;  // delegate these to _shared
    T* operator->() const;
};
希望上面唯一模棱两可的点是故意的。