const 与 shared_ptr

const 与 shared_ptr

注意: 需要c++11的支持

const 与 shared_ptr 之间的组合不是很常见,最多的也只是在传递参数时:

shared_ptr<int> func(const shared_ptr<int> &ptr) {
	*ptr += 1;

	return ptr;
}

这里的 const shared_ptr<int> &ptr和常规的 const T &p一样,这里的const都是顶层const,也就是说我们不能改变ptr的地址,也不能改变p的值。

常规的内置指针和const有以下组合:

	constexptr int a = 5;  // a定义在函数体之外。
	
	const int *ptr1 = &a;             // 指向整型常量 的 指针
	int const *ptr2 = &a;             // 指向整型    的 常量指针
	const int const *ptr3 = &a;       // 指向整型常量 的 常量指针
	constexpr int *ptr4 = &a;         // 指向整型    的 常量指针
	constexpr const int *ptr5 = &a;   // 指向整型常量 的 常量指针

shared_ptr与const也有一下组合:

    int a = 5;

	const shared_ptr<int> ptr1 = make_shared<int>(a);        // 指向整型    的 常量智能指针
	shared_ptr<const int> ptr1 = make_shared<int>(a);        // 指向整型常量 的 智能指针
	const shared_ptr<const int> ptr3 = make_shared<int>(a);  // 指向整型常量 的 常量智能指针
  • 3
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值