c++ - 带有 std::shared_ptr 的数组索引符号到数组

标签 c++ smart-pointers

我正在编写一些通过内部函数使用 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];) 并将其编入索引。

关于c++ - 带有 std::shared_ptr 的数组索引符号到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29613893/

相关文章:

c++ - static_assert 如果表达式是 constexpr

c++ - CButton封装按钮按下事件处理

C++03 带 free() 的智能指针

c++ - 如何更改以避免复制指针的内容

c++ - 什么是 boost::ptr_vector::pop_front() 返回类型?

c++ - 多个 vtables,在打电话时以错误的方式结束

c++ - boost:bind 和 io_service 在两个不同的类中

c++ - SDL——跨平台开发

c++ - C++ 中的读写线程安全智能指针,x86-64

c++ - .get() 和 -> 与智能指针之间有区别吗?