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



我想我误解了智能指针。请看以下示例。当我使用 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>,则工作正常。

最新更新