我正在尝试通过其指针访问数组的元素,声明如下shared_ptr:
#include <iostream>
#include <memory>
using namespace std;
int main()
{
{
shared_ptr<int> up(new int[5] {1,2,3,4,5});
cout << up[3];
}
getchar();
return 0;
}
但是,在编译时,会抛出一个错误,指出“没有[]与这些操作数对应的运算符”。
我在cppreference和 IDE 工具提示中读到[]y运算符shared_ptr采用 type ptrdiff_t,但是像这样:
#include <iostream>
#include <memory>
using namespace std;
int main()
{
{
shared_ptr<int> up(new int[5] {1,2,3,4,5});
cout << up[static_cast<ptrdiff_t>(3)];
}
getchar();
return 0;
}
也因同样的错误而失败。
问题:如何正确使用此运算符,我做错了什么?
您的第一个错误是尝试
std::shared_ptr<int>使用通过分配的数组进行初始化new int[]。这是不正确的,因为它在释放内存时shared_ptr<T>调用,而不是必需的.deletedelete[]替换
int为int[]解决了这个问题和你的问题 - 智能指针了解数组实际包含的内容并允许对其进行索引。