关注
#include <iostream>
using namespace std;
template<class T>
class SmartPtr
{
public:
SmartPtr(T *p){
try
{
use_count = new int(1);
}
catch (...)
{
delete ptr;
ptr = nullptr;
use_count = nullptr;
cout << "Allocate memory for use_count fails." << endl;
exit(1);
}
cout << "Constructor is called!" << endl;
}
~SmartPtr(){
// 只在最后一个对象引用ptr时才释放内存
if (--(*use_count) == 0)
{
delete ptr;
delete use_count;
ptr = nullptr;
use_count = nullptr;
cout << "Destructor is called!" << endl;
}
}
SmartPtr(const SmartPtr<T> &orig){
// 浅拷贝
ptr = orig.ptr;
use_count = orig.use_count;
++(*use_count);
cout << "Copy constructor is called!" << endl;
}
SmartPtr<T>& operator=(const SmartPtr<T> &rhs){
// 浅拷贝
++(*rhs.use_count);
// 将左操作数对象的使用计数减1,若该对象的使用计数减至0,则删除该对象
if (--(*use_count) == 0)
{
delete ptr;
delete use_count;
cout << "Left side object is deleted!" << endl;
}
ptr = rhs.ptr;
use_count = rhs.use_count;
cout << "Assignment operator overloaded is called!" << endl;
return *this;
}
private:
T *ptr;
// 将use_count声明成指针是为了方便对其的递增或递减操作
int *use_count;
};
int main()
{
// Test Constructor and Assignment Operator Overloaded
SmartPtr<int> p1(new int(0));
p1 = p1;
// Test Copy Constructor
SmartPtr<int> p2(p1);
// Test Assignment Operator Overloaded
SmartPtr<int> p3(new int(1));
p3 = p1;
cin.get();
return 0;
}
查看原帖
点赞 评论
相关推荐
10-12 11:32
广东外语外贸大学 网页产品经理 点赞 评论 收藏
分享
点赞 评论 收藏
分享
牛客热帖
- 1... 最有挫败感的一件事1.0W
- 2... 你就天天围着秋招转吧,饭也不用吃了,课也不用上了,就天天思考它到底发不发offer,把人想废,把身体想烂,把爱好全部荒废,每天就无时无刻的看邮箱有没有新邮件。你就看你***就得了。如果你还有脑子,那么不管什么时候看到这句话都该去做自己该做的事,你的肩上还有人类的希望,你的背后还有很多群友爱你。你可以继续这样把自己压垮,直到失去所有曾经引以为傲的东西——你的学习能力、你的热情、你的身体健康,甚至你的梦想。你每天守着邮箱等待的,不是成功的钥匙,而是徒增的焦虑和无尽的自责。是时候停下来,问问自己:这真的值得吗?如果你还记得那些曾经驱动你的梦想,那些让你熬夜苦读、让你为之奋斗的目标,那么你就该意识到,秋招只是你人生中一个节点,而不是全部。没有哪个Offer能定义你的一生,你也不需要为了这一时的得失,丢掉对生活和学习的热情。你是值得被爱,被认可的。那些关心你的人不希望你被秋招的压力吞噬,他们希望看到一个满怀信心、活力四射的你。肩上的责任不仅仅是一个工作机会,而是为自己和未来的生活去不断努力,保持平衡,拥有健康的身心。放下手机,关闭邮箱,去做让你真正快乐、充实的事。读书、学习、运动、发展自己的兴趣,这些都将为你的人生铺平道路。当你真正成长为一个内心强大、自信满满的人,机会自然会到来1.0W
- 3... 选择国央企了8003
- 4... 10.15 百度笔试5970
- 5... #浪潮求职进展汇总# 一面过了但是心理测评一直没过,做了四次都没过,hr看不下去了亲自帮我把测评做了5180
- 6... 美团 java后端 1面4846
- 7... 秋招结束,写个总结4844
- 8... 数字马力一面(后端开发工程师)4191
- 9... 韶音科技毁意向!一生黑!切忌all in4169
- 10... 秋招大抵是完蛋了4011
正在热议
# offer帮选 #
140069次浏览 1516人参与
# 写简历别走弯路 #
574207次浏览 7144人参与
# 平安产险科技中心求职汇总 #
45780次浏览 488人参与
# 得物求职进展汇总 #
31069次浏览 493人参与
# 面试中的破防瞬间 #
168350次浏览 1878人参与
# 0offer是寒冬太冷还是我太菜 #
730790次浏览 6864人参与
# 叠纸游戏校招 #
24059次浏览 341人参与
# 你觉得今年秋招难吗 #
945382次浏览 13042人参与
# 选了这个offer,你有没有后悔? #
255839次浏览 2254人参与
# 我的成功项目解析 #
178149次浏览 4076人参与
# 我的简历长这样 #
1602167次浏览 25257人参与
# 无实习如何秋招上岸 #
586554次浏览 7300人参与
# 投递几十家公司,到现在0offer,大家都一样吗 #
43508次浏览 367人参与
# 韶音科技求职进展汇总 #
27821次浏览 350人参与
# 你觉得技术面多长时间合理? #
31920次浏览 213人参与
# 机械人的offer怎么选 #
28181次浏览 247人参与
# 非技术岗薪资爆料 #
128008次浏览 1186人参与
# 硬件人的简历怎么写 #
201660次浏览 2626人参与
# 你觉得找工作该拿大厂还是小厂练手 #
134192次浏览 1562人参与
# 实习,投递多份简历没人回复怎么办 #
2172070次浏览 32478人参与
# 你是怎么缓解秋招焦虑的? #
72757次浏览 699人参与
# 小红书求职进展汇总 #
20070次浏览 145人参与