1 Star 0 Fork 1

dhs347/cppstudy

forked from Huoty/cppstudy 
加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
test_shared_ptr.cpp 1.67 KB
一键复制 编辑 原始数据 按行查看 历史
Huoty 提交于 2024-12-08 23:34 +08:00 . update at 20241208233432
/*
* Copyright (c) Huoty, All rights reserved
* Author: Huoty <sudohuoty@163.com>
* CreateTime: 2020-08-19 22:23:50
*
*/
#include <iostream>
#include <memory> // 使用 shared_ptr 需要 include 它
using namespace std;
int main(void)
{
// 通过 make_shared 创建 shared_ptr
std::shared_ptr<int> p1 = std::make_shared<int>();
*p1 = 78;
std::cout << "p1 = " << *p1 << std::endl;
// 查看引用计数
std::cout << "p1 Reference count = " << p1.use_count() << std::endl;
// 第二个 shared_ptr 也将在内部指向相同的指针
// 这将会使引用计数变为 2
std::shared_ptr<int> p2(p1);
// 查看引用计数
std::cout << "p2 Reference count = " << p2.use_count() << std::endl;
std::cout << "p1 Reference count = " << p1.use_count() << std::endl;
// 比较智能指针
if (p1 == p2) {
std::cout << "p1 and p2 are pointing to same pointer\n";
}
std::cout << "Reset p1" << std::endl;
// 重置 shared_ptr,在这种情况下,其内部不会指向内部的任何指针
// 因此其引用计数将会变为 0
p1.reset();
std::cout << "p1 Reference Count = " << p1.use_count() << std::endl;
// 重置 shared_ptr,在这种情况下,其内部将会指向一个新的指针
// 因此其引用计数将会变为1
p1.reset(new int(11));
std::cout << "p1 Reference Count = " << p1.use_count() << std::endl;
// 分配 nullptr 将取消关联指针并使其指向空值
p1 = nullptr;
std::cout << "p1 Reference Count = " << p1.use_count() << std::endl;
if (!p1) {
std::cout << "p1 is NULL" << std::endl;
}
// 定义时还可以用 auto 简化
auto p3 = std::make_shared<int>();
cout << "p3 Reference Count = " << p3.use_count() << endl;
return 0;
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/dhs347/cppstudy.git
git@gitee.com:dhs347/cppstudy.git
dhs347
cppstudy
cppstudy
master

搜索帮助