Question

Here is a code I do have on Visual 2013. I need to have an aligned new. I can not allocate only because A CTOR does something useful.

Any idea of why this does not compile ?

#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;
}

solution

template<typename T>
struct aligned_delete {
  void operator()(T* ptr) const {
    _mm_free(ptr);
  }
};
Was it helpful?

Solution

aligned_delete<A> is a function, not a type.

Make a type with an overloaded function call operator:

template<typename T>
struct aligned_delete {
    void operator()(T* ptr) const {
        _mm_free(ptr);
    }
};

OTHER TIPS

Your exception handling is a bit off, you will leak the allocated memory if construction fails. It also has undefined behavior if _mm_malloc returns nullptr. Try:

template<typename T, std::size_t alignment>
inline T* aligned_new(){
    void* ptr = _mm_malloc(sizeof(T), alignment);
    if (ptr) {
        try {
            return new (ptr) T;
        } catch(...) {
            _mm_free(ptr);
            throw;
        }
    }
    // throw std::bad_alloc();
    return nullptr;
}

(Yes, this is not an answer - it's an overlong comment.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top