why is aligned and not aligned version of operator delete always incompatible ? let think - how is possible allocate align on some value memory ? we initially always allocate some memory block. for return align pointer to use - we need adjust allocated memory pointer to be multiple align. ok. this is possible by allocate more memory than requested and adjust pointer. but now question - how free this block ? in general user got pointer not to the begin of allocated memory - how from this user pointer jump back to begin of allocated block ? without additional info this is impossible. we need store pointer to actual allocated memory before user returned pointer. may be this will be more visible in code typical implementation for aligned new and delete use _aligned_malloc and _aligned_freevoid* operator new(size_t size, std::align_val_t al){ return _aligned_malloc(size, static_cast<size_t>(al));}void operator delete (void * p, std::align_val_t al){ _aligned_free(p);}未对齐时 new 和 delete 使用 malloc 和 freevoid* operator new(size_t size){ return malloc(size);}void operator delete (void * p){ free(p);}现在让我们寻找 _aligned_malloc 和 _aligned_freenow let look for internal implementation of _aligned_malloc and _aligned_freevoid* __cdecl _aligned_malloc(size_t size, size_t alignment){ if (!alignment || ((alignment - 1) & alignment)) { // alignment is not a power of 2 or is zero return 0; } union { void* pv; void** ppv; uintptr_t up; }; if (void* buf = malloc(size + sizeof(void*) + --alignment)) { pv = buf; up = (up + sizeof(void*) + alignment) & ~alignment; ppv[-1] = buf; return pv; } return 0;}void __cdecl _aligned_free(void * pv){ if (pv) { free(((void**)pv)[-1]); }}一般而言, _aligned_malloc 分配 size + sizeof(void *)+对齐方式-1 ,而不是调用方 size 所请求.调整分配的指针以适合对齐方式,并在指针返回到调用者之前存储最初分配的内存.in general words _aligned_malloc allocate size + sizeof(void*) + alignment - 1 instead requested by caller size. adjust allocated pointer to fit alignment , and store originally allocated memory before pointer returned to caller.和 _aligned_free(pv)调用不是 free(pv),而是 free(((void **)pv)[-1]); -用于总是另一个指针.因为 _aligned_free(pv)的这种效果总是与另一个 free(pv)进行比较.和 operator delete(pv,al); 始终与 operator delete(pv); 不兼容,如果说 delete [] 通常具有相同的效果作为 delete 删除,但align vs not align的运行时间总是不同的.and _aligned_free(pv) call not free(pv) but free(((void**)pv)[-1]); - for always another pointer. because this effect of _aligned_free(pv) always another compare free(pv). and operator delete(pv, al); always not compatible with operator delete(pv); if say delete [] usual have the same effect as delete but align vs not align always run time different. 这篇关于如何正确调用对齐的新/删除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 06-12 12:42