【发布时间】:2016-01-30 06:16:35
【问题描述】:
我正在编写一些通过内部函数使用 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> ]
有没有办法做到这一点?我对使用智能指针还是很陌生,所以我可能会搞砸一些简单的事情。感谢您的帮助!
【问题讨论】:
-
旁白:您的分配函数不会在数组中构造对象,并且在清理时不会调用析构函数。你应该小心只在微不足道的类型上使用它——或者更好的是,在函数中做一个
static_assert以确保std::is_trivial<T>::value是true(我认为这是你想要做的检查)。或者甚至更好,使用 SNIFAE 从重载中消除非平凡类型。或者,更改函数以适当地构造和销毁对象。 -
为什么在喜欢对齐的类中没有重载运算符 new / delete?
-
我认为您不能将 allocate_aligned 与
float[]一起使用,因为 sizeof 不能应用于此。 -
@typ1232:你说得对,
T应该是简单的float,返回类型是std::shared_ptr<T[]> -
@Hurkyl 我只是在浮点数、双精度数和复杂数组(复杂实现为 2 个浮点数的结构)上使用它,所以这应该不是问题,但我应该在那里添加一个检查.好主意,谢谢。
标签: c++ smart-pointers