shared_ptr<int>数组的元素 (shared_ptr<int[]>)
shared_ptr<int> to an element of an array (shared_ptr<int[]>)
我目前正在学习智能指针,并且从"正常"指针过渡时遇到了一些麻烦。我想知道是否可以将共享_ptr从指向共享_ptr数组中的元素的函数返回?
在主函数中,我声明了一个int数组:
shared_ptr<int[]> arr(new int[size]);
我想创建的功能将返回共享_ptr到数组的最小元素:
shared_ptr<int> getSmallestElement(shared_ptr<int[]> arr, int size) {
int smallestValue = arr[0], smallestIndex = 0;
for (int i = 1; i < size; i++) {
if (smallestValue > arr[i]) {
smallestValue = arr[i];
smallestIndex = i;
}
}
// what would be the equivalent shared_ptr code for the code below?
int *returnPointer = arr[smallestIndex];
return returnPointer;
}
我得到的最接近,但这是我的普通指针的逻辑是:
shared_ptr<int> returnPointer = arr.get() + smallestIndex;
return returnPointer;
甚至可以使用共享_ptr进行此操作,还是使用unique_ptr的首选方式?
您需要使用混叠构造函数,以维持所有权关系:
shared_ptr<int> returnPointer{arr, *arr + smallestIndex};
请注意,您不能直接将下标运算符与共享指针使用。您需要首先间接它,以便下标运算符适用于数组:(*arr)[i]
相关文章:
- 为什么在全局范围内使用"extern int a"似乎不行?
- int(c) 和 c-'0' 之间的区别。C++
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 为什么野牛仍在使用"int yylex(void)",却找不到"int yylex(YYS
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 是否可以从int转换为enum类类型
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- 'short int'持有的值溢出,但"自动"不会溢出?
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 调用'begin(int [n])'没有匹配函数
- 没有显式声明的int[]中的foreach
- 在c++中访问int到类对象的映射时出错
- 为什么我无法更改"set<set>"循环中的值<int>
- 长 长 int 不要 长 int 好
- C++程序在循环后给出奇怪的int值
- 如何计算数据类型的范围,例如int
- 如果"new int"返回"int*",那么为什么"new int[n]"不返回"int**"?
- 如何在cpp.中使用协议缓冲区存储大缓冲区/数组(char/int)