这是我在 Visual 2013 上拥有的代码。 我需要有一个对齐的新的。 我不能仅仅因为 CTOR 做了一些有用的事情就进行分配。
知道为什么这不能编译吗?
#include <memory>
#include <emmintrin.h>
struct A{
A():b(0){b++;}
int b;
};
template<typename T,int alignment>
inline T* aligned_new(){
try{
T*ptr = reinterpret_cast<T*>(_mm_malloc(sizeof(T),alignment));
new (ptr) T;
return ptr;
}
catch (...)
{
return nullptr;
}
}
template<typename T>
inline void aligned_delete(T*ptr){
_mm_free(ptr);
}
int main(int argc, char * argv[]){
std::unique_ptr<A, aligned_delete<A>> var(aligned_new<A,16>);
return 0;
}
解决方案
template<typename T>
struct aligned_delete {
void operator()(T* ptr) const {
_mm_free(ptr);
}
};
最佳答案
aligned_delete<A>
是一个函数,而不是一个类型。
使用重载函数调用运算符创建类型:
template<typename T>
struct aligned_delete {
void operator()(T* ptr) const {
_mm_free(ptr);
}
};
关于c++11 - _mm_free 作为 unique_ptr 的删除器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20563628/