C++智能指针——释放和转换裸指针

	//初始化
	int* a = new int();
	shared_ptr<int> ptr(a);

	shared_ptr<int> ptr1 = make_shared<int>(12);
		
	shared_ptr<int> ptr2(new int());
	//

	shared_ptr<int> ptr3(ptr1);

	//转裸指针
	int *a=ptr1.get();

	int b = *ptr1;
	ptr1.unique();//判断是否是唯一的共享指针

	ptr1.swap(ptr2);//交换

	ptr1.reset();//只有当引用计数为零才会清掉,不然它只会降维
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++中,智能指针之间的类型转换可以通过以下几种方式实现: 1. 隐式转换:如果两个智能指针类型具有相同的底层指针类型,可以直接进行隐式转换。例如,可以将`shared_ptr`隐式转换为`unique_ptr`。 ```cpp std::shared_ptr<int> sharedPtr = std::make_shared<int>(10); std::unique_ptr<int> uniquePtr = sharedPtr; // 隐式转换 ``` 2. 显式转换:可以使用`static_pointer_cast`、`dynamic_pointer_cast`和`const_pointer_cast`等函数进行显式类型转换。 - `static_pointer_cast`用于在两个相关类型之间进行转换,不会进行运行时类型检查。 - `dynamic_pointer_cast`用于在两个相关类型之间进行转换,并进行运行时类型检查。如果转换失败,返回空智能指针。 - `const_pointer_cast`用于在智能指针之间进行const或volatile修饰符的转换。 ```cpp std::shared_ptr<Base> sharedPtr = std::make_shared<Derived>(); std::shared_ptr<Derived> derivedPtr = std::dynamic_pointer_cast<Derived>(sharedPtr); // 显式转换 ``` 3. 使用`reinterpret_pointer_cast`:如果需要进行底层指针的重新解释转换,可以使用`reinterpret_pointer_cast`函数。但请注意,这种方式是非标准的,并且可能导致未定义的行为。 ```cpp std::shared_ptr<int> sharedPtr = std::make_shared<int>(10); std::shared_ptr<float> floatPtr = std::reinterpret_pointer_cast<float>(sharedPtr); // 重新解释转换 ``` 需要注意的是,在进行智能指针类型转换时,请确保转换的正确性,以避免潜在的内存安全问题。同时,尽量避免使用`reinterpret_pointer_cast`,以确保代码的可移植性和安全性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值