将`char*`与`delete`解除分配 - 内存泄漏?

Vit*_*meo -2 c++ memory memory-management c++11

template<typename T> char* allocateSomething()
{
    return reinterpret_cast<char*>(std::allocator<T>{}.allocate(1));
}

void deallocateSomething(char* mPtr) { delete mPtr; }

struct TestType { ... };

int main()
{
    char* ptr{allocateSomething<TestType>()};
    deallocateSomething(ptr);   
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

是否可以保证deallocateSomething(ptr)释放所有已分配的字节,即使它typename T在调用时不知道使用的是什么allocateSomething<T>()

还是有必要模板化deallocateSomething

编辑:我手动处理对象的构造/销毁.


编辑2:这会正常工作吗?

template<typename T> char* allocateSomething()
{
    return reinterpret_cast<char*>(std::malloc(sizeof(T)));
}

void deallocateSomething(char* mPtr) { std::free(mPtr); }

// ...
Run Code Online (Sandbox Code Playgroud)

Jon*_*ely 8

是否保证deallocateSomething(ptr)将释放所有已分配的字节,即使它不知道调用allocateSomething()时使用的typename T?

不,没有任何保证,这是未定义的行为.

或者是否有必要对deallocateSomething进行模板化?

是的,总的来说.

您必须使用匹配的分配/释放方法.如果你想解除分配,delete你必须分配new.如果你改变分配所以它不使用std::allocator(你无法控制,也不知道它是如何分配的)而是分配,new char[sizeof(T)]那么你可以安全地释放delete[](但不是delete!你必须使用[])