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

Why am I losing these constructed objects with smart pointers, but not new?

我想我对智能指针有一些误解。看看下面的例子。当我使用 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;
}

您正在用定义

隐藏外部作用域的 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.