首页 > 解决方案 > 为什么我用智能指针丢失了这些构造的对象,但不是新的?

问题描述

我想我对智能指针有一些误解。看看下面的例子。当我使用 new/*时,我得到了我所期望的,但是当我使用时std::shared_ptr,我得到一个空指针错误。智能指针的实现不等同于我对 new/ 所做的*吗?

另外,我可以调整AnotherGiver以避免许多指针取消引用吗?

#include <memory>
#include <iostream>
class numGiver
{
public:
    virtual int giveNum(void) = 0;
    virtual int othNum(void) = 0;
};


class constGiver : public numGiver
{
public:
    int giveNum(void)
    {
        return 5;
    }
    int othNum(void)
    {
        return 5;
    }
};


class othAddGiver : public numGiver
{
public:
    int giveNum(void)
    {
        return myNum + ng->giveNum();
    }
    int othNum(void)
    {
        return ng->othNum();
    }
    othAddGiver(std::shared_ptr<numGiver> ng, int num) : ng(ng), myNum(num) {};
private:
    std::shared_ptr<numGiver> ng;
    int myNum;
};

class AnotherGiver : public numGiver
{
public:
    int giveNum(void)
    {
        return myNum + ng->giveNum();
    }
    int othNum(void)
    {
        return ng->othNum();
    }
    AnotherGiver(numGiver* ng, int num) : ng(ng), myNum(num) {};
private:
    numGiver* ng;
    int myNum;
};


int main()
{
    std::shared_ptr<numGiver> ng = std::make_shared<constGiver>();
    std::shared_ptr<numGiver> og;
    numGiver* anotherGiver = 0;
    for (int i = 0; i < 25; ++i)
    {
        if (i == 0)
        {
            anotherGiver = new AnotherGiver(&*ng, 3);
            std::shared_ptr<numGiver> og = std::make_shared<othAddGiver>(ng, 3);
        }
        else
        {

            anotherGiver = new AnotherGiver(anotherGiver, 3);
            std::shared_ptr<numGiver> og = std::make_shared<othAddGiver>(og, 3);
        }

    }
    std::cout << anotherGiver->giveNum() << std::endl;
    std::cout << anotherGiver->othNum() << std::endl;
    std::cout << og->giveNum() << std::endl;
    std::cout << og->othNum() << std::endl;
    return 0;
}

标签: c++smart-pointers

解决方案


您正在og使用定义遮蔽外部范围

std::shared_ptr<numGiver> og = std::make_shared<othAddGiver>(ng, 3);

std::shared_ptr<numGiver> og = std::make_shared<othAddGiver>(og, 3);

如果你std::shared_ptr<numGiver>从这些行中删除,它工作正常。


推荐阅读