[英]Accessing array of shared_ptr
#include <memory>
int main()
{
std::shared_ptr<double> array (new double [256], [](double * d){
delete [] d;
});
}
I made a shared_ptr
pointing into an array of doubles which has its own custom deleter.我创建了一个shared_ptr
指向一个双精度数组,它有自己的自定义删除器。
Now how can I access the array?现在我如何访问数组? Let's say I wish to access the array at index 1
.假设我希望访问索引1
处的数组。 I tried the usual "bracket method" but I get errors.我尝试了通常的“括号方法”,但出现错误。
The word array
points to its first element by default, but what if I want to access the 2nd element?词array
默认指向它的第一个元素,但是如果我想访问第二个元素怎么办? Using increments and bracket gives me the "no match for operator" error.使用增量和括号给了我“不匹配运算符”错误。
Can someone explain to me what's happening under the hood?有人可以向我解释引擎盖下发生了什么吗?
I am asking this for research purposes, despite being aware that unique_ptr
and vector
will do a better job.尽管我知道unique_ptr
和vector
会做得更好,但我还是出于研究目的提出这个要求。
The bracket notation is defined to work with pointer types (and you're right that, given array array
, the expression array
decays to an expression with such a type which points to the first element) but, despite its function, std::shared_ptr
is not a pointer type .括号表示法被定义为与指针类型一起使用(并且您是对的,给定数组array
,表达式array
衰减为具有指向第一个元素的类型的表达式)但是,尽管它具有功能, std::shared_ptr
不是指针类型。
You would have to obtain the raw pointer first :您必须首先获得原始指针:
array.get()[n];
Where n
is, of course, a valid array subscript.其中n
当然是一个有效的数组下标。
This is also the case with std::unique_ptr
(though note that, in that case, you do not need to supply your own deleter! ).这也是std::unique_ptr
的情况(但请注意,在这种情况下,您不需要提供自己的删除器! )。
in C++17, support for array of shared_ptr like in unique_ptr( c++11).在 C++17 中,像 unique_ptr(c++11) 一样支持 shared_ptr 数组。
int main()
{
std::shared_ptr<double[]> array1 (new double [3]{4,5,6}, [](double * d){
delete [] d;});
std::unique_ptr<double[]> array2 (new double [3]{4,5,6}, [](double * d){
delete [] d });
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.