我正在编写一些通过内部函数使用 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[]
必须作为成员实现。
但是,您可以通过以下三个选项之一获得非常接近的效果:
只需使用具有正确对齐方式的成员类型的
vector
(例如xmmintrin.h
中的__m128
)并删除所有其他工作。自己实现一个类似于
shared_ptr
的类(可能在后台使用std::shared_ptr
)在需要时提取原始指针 (
float testVar = input.get()[5];
) 并将其编入索引。
关于c++ - 带有 std::shared_ptr 的数组索引符号到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29613893/