数组索引表示法,其中 std::shared_ptr 到数组

array index notation with std::shared_ptr to an array

本文关键字:数组 shared ptr 其中 索引 表示 std      更新时间:2023-10-16

我正在编写一些通过内部函数使用 SSE/AVX 的代码。因此,我需要保证对齐的数组。我正在尝试使用以下代码通过_aligned_malloc进行这些操作:

template<class T>
std::shared_ptr<T> allocate_aligned( int arrayLength, int alignment )
{
   return std::shared_ptr<T>( (T*) _aligned_malloc( sizeof(T) * arrayLength, alignment ), [] (void* data) { _aligned_free( data ); } );
}

我的问题是,如何使用通常的数组索引表示法引用数组中的数据?我知道unique_ptr专门用于调用 delete[] 进行销毁并允许数组索引符号(即myArray[10]访问数组的第 11 个元素)的数组。但是,我需要使用shared_ptr。

这段代码给我带来了问题:

void testFunction( std::shared_ptr<float[]>& input )
{
   float testVar = input[5]; // The array has more than 6 elements, this should work
}

编译器输出:

error C2676: binary '[' : 'std::shared_ptr<_Ty>' does not define this operator or a conversion to a type acceptable to the predefined operator
1>          with
1>          [
1>              _Ty=float []
1>          ]

有没有办法做到这一点?我对使用智能指针仍然很陌生,所以我可能会搞砸一些简单的东西。感谢您的任何帮助!

真正想要的,在C++中实际上是不可能的。

原因很简单:shared_ptr没有为他们实施operator[]operator[]必须作为成员实施。

但是,您可以通过以下三个选项之一非常接近:

  1. 只需使用具有正确对齐方式的杆件类型的vector(例如 从xmmintrin.h __m128 )并删除所有其他工作。

  2. 实现一个类似于自己shared_ptr类(可能在引擎盖下使用std::shared_ptr

  3. 在需要时提取原始指针(float testVar = input.get()[5]; ),并改为为其编制索引。

对于那些面临类似问题的人,以下内容可能会有所帮助。不要使用指向数组的共享指针,而是使用指向指针的共享指针。您仍然可以使用索引表示法,但在此之前需要取消引用共享指针:

std::shared_ptr<int*> a = std::make_shared<int*>(new int[10]);
(*a)[0] = 5;
std::cout << (*a)[0] << std::endl;