智能指针 shared_ptr 使用

C++ shared_ptr 使用总结:

class Color
{
public:
    Color(uint32_t _red, uint32_t _yellow, uint32_t _green)
            : mRed(_red)
            , mYellow(_yellow)
            , mGreen(_green)
    {

    }

    const uint32_t getRed() {
        return mRed;
    }
    const uint32_t getYellow() {
        return mYellow;
    }
    const uint32_t getGreen() {
        return mGreen;
    }

private:
    uint32_t mRed;
    uint32_t mYellow;
    uint32_t mGreen;
};

 

1. 初始化三种方式

    shared_ptr<Color> pPtr1 = make_shared<Color>(4,4,2, "make_shared consruct"); // method 1
    shared_ptr<Color> pPtr2(new Color(4,5,2, "initialize list"));               // method 2
    shared_ptr<Color> pPtr3(nullptr);                                           // method 3
    pPtr3 = make_shared<Color>(4,4,2,"copy construct");

 

2. 指针使用:可以直接当做普通使用,调用对应的函数或者变量

    cout << pPtr1->getRed() << endl;
    cout << pPtr2->getYellow() << endl;
    cout << pPtr1->getGreen() << endl;

 

 3. 当一个智能指针被重新赋值后,它以前指向的数据的use_count就会减1,如果减到0后,就会释放其内存;

    weak_ptr<Color> pWeakPtr = pPtr1;
    pPtr1 = pPtr2;
    cout << pWeakPtr.use_count() << endl;

 当输出的值为0时,表示前面指向的数据被释放掉了。

 

注:智能智能存在的问题:

1. 当类中的 uint32_t 变成 u_int8(unsigned char)后,上诉1,2步骤后,得不到对应值。

2. 但是使用裸指针获取没有问题。

posted @ 2021-12-07 16:06  王清河  阅读(97)  评论(0编辑  收藏  举报