c++ - 为什么我用智能指针丢失了这些构造的对象,但不是新的?
问题描述
我想我对智能指针有一些误解。看看下面的例子。当我使用 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>
从这些行中删除,它工作正常。
推荐阅读
- java - Spring @Sql Annotations,可以在所有测试之前运行一次吗?
- node.js - RestApi Oauth 504“不是有效的 Bcrypt 哈希。” 问题使用:Nodejs + Expressjs + Postgresql
- java - Unsafe#staticFieldBase 抛出 IllegalArgumentException 而没有消息
- cypress - 执行登录时遇到错误:[auth/popup-blocked] 无法与弹出窗口建立连接。可能被浏览器屏蔽了
- assembly - 在没有 CMP 的情况下检查结果是否为 0?组装 x86 MASM
- mysql - 始终通过 MySQL 函数传递列来加密和解密
- apache-spark - 步骤开始运行后在哪里获取 EMR 集群故障日志
- flutter - Flutter:为什么定位小部件在 TextField 上是透明的?
- batch-file - 如何在文件名中搜索和替换具有不同扩展名的多个文件的特定文本?
- node.js - 为什么 docker 中的 npm 重建工作但 npm install 没有