首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++智能指针类

C++智能指针类
EN

Code Review用户
提问于 2015-05-10 00:09:57
回答 1查看 144关注 0票数 0
代码语言:javascript
复制
#include <iostream>

template <typename T>
class my_smart_ptr {
    T* raw;
    unsigned * p_count;
public:
    my_smart_ptr(T* t):
    raw(t),
    p_count (new unsigned(1))
    {

    }

    my_smart_ptr(const my_smart_ptr<T> & p):
    raw(p.raw),
    p_count(p.p_count)
    {
        ++(*p_count);
    }

    const my_smart_ptr<T> & operator=(const my_smart_ptr<T>& p)
    {
        if (p == *this)
        {
            return *this;
        }

        raw = p.raw;
        --(*p_count);
        ++(*(p.p_count));
        return *this;

    }

    ~my_smart_ptr()
    {
        --(*p_count);
        if (*(p_count) == 0)
        {
            delete raw;
        }
    }
};


class A{
public:

    A()
    {
        std::cout<< "A()" << std::endl;
    }

    ~A()
    {
        std::cout<< "~A()" << std::endl;
    }

};
int main()
{
    my_smart_ptr<A> a (new A);
    return 0;
}
EN

回答 1

Code Review用户

发布于 2015-05-10 05:13:52

operator=中有一个错误。当函数返回时,LHS的p_count成员仍然指向旧的p_count。它应该等于RHS的p_count。此外,当计数达到零时,忘记释放旧数据。

代码语言:javascript
复制
const my_smart_ptr<T> & operator=(const my_smart_ptr<T>& p)
{
    if (p == *this)
    {
        return *this;
    }

    // Keep a copy of the old values.
    // Don't change these until the state of the
    // object has been made consistent.
    unsigned*  oldCount = p_count;
    T*         oldRaw   = raw;

    // Update the state of the object.
    // Making sure to get the local count correct.
    raw = p.raw;
    p_count = p.p_count;  // Without this the use count is incorrect.
    ++(*(p.p_count));

    // Now clean up the old state.
    --*oldCount;
    if (*oldCount == 0) {
        delete oldCount;
        delete oldRaw;
    }
    return *this;
}

operator=函数通常返回一个非const引用。毕竟,您只是修改了对象。

代码语言:javascript
复制
my_smart_ptr<T> & operator=(const my_smart_ptr<T>& p) { ... }
票数 1
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/90282

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档