1d 智能指针不适用于语法 (*)++

1d Smart Pointer doesn't work with syntax (*)++

本文关键字:语法 适用于 智能 指针 不适用 1d      更新时间:2023-10-16

我正在学习智能指针。所以,我有箭头代码,我不明白。代码如下所示。我在visualstudio2019中尝试了以下代码。为什么我不能使用增量运算符(*i(++,因为我可以使用i[0]++。

shared_ptr<int[]> foo(shared_ptr<int[]>i)
{
cout << i << 'n';
(*i)++;             // doesn't        but works for shared_ptr<int>i as argument
i[0]++;            //  works             
*i += 1;          // <--  doesn't  work
i[0] += 1;        // <--- works 
return i;
}
int main(int argc)
{

auto start = chrono::high_resolution_clock::now();
// int T;
//cin >> T;
// while (T--)
//  {
std::unique_ptr<int[]> pointer(new int[5]);                 // <-- can  do it 
for (int i = 0; i < 5; ++i) pointer[i] = i;
auto pointer3 = make_unique<int[] >(new int[5]);  // <--- can't do it Okay i know that there is no overload but what's reason for not having ?
cout << pointer << 'n';
auto pointer1 = std::move(pointer);
cout << pointer1 << 'n';
auto shrd_ptr = foo(std::move(pointer1));
cout << shrd_ptr << 'n';
//  }
auto end = chrono::high_resolution_clock::now();
cout << std::chrono::duration_cast<std::chrono::milliseconds>(end -start).count() <<'n';
return 0;
}

错误列表:

Error C2088   '++': illegal for class 
Error C2100   illegal indirection 
Error (active)    E0349   no operator "*" matches these operands  
Error (active)    E0349   no operator "*" matches these operands  
Error (active)    E0042   no instance of overloaded fucntion "make_unique" matches the argument list

如果shared_ptr存储了一个数组,则(并且仅限于此(shared_ptr::operator[]提供对存储数组的各个元素的访问。

CCD_ 3提供对整个存储对象的访问。它是为所有类型的存储对象定义的。如果这是一个数组,那么这就是整个数组。

这是对标准C/C++数组/指针语义的有意偏离,其中*xx[0]在定义上是一回事。shared_ptr不会这样做,因为它的设计者不希望它这样做。