代码之家  ›  专栏  ›  技术社区  ›  Carbon

为什么我会丢失这些带有智能指针但不是新的构造对象?

  •  1
  • Carbon  · 技术社区  · 7 年前

    我想我误解了一些聪明的指点。请看下面的示例。当我使用新的/ * 我得到了我所期望的,但是当我使用 std::shared_ptr ,我得到一个空指针错误。智能指针实现是否与我用新的方法所做的相同?/ * ?

    另外,我能调整吗 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;
    }
    
    1 回复  |  直到 7 年前
        1
  •  3
  •   Caleth    7 年前

    你在跟踪外窥镜 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> 从这些线条来看, works fine.