说我有以下C++:
char *p = new char[cb];
SOME_STRUCT *pSS = (SOME_STRUCT *) p;
delete pSS;
Run Code Online (Sandbox Code Playgroud)
根据C++标准,这是安全的吗?我需要回头char*再使用delete[]吗?我知道它在大多数C++编译器中都有效,因为它是普通的普通数据,没有析构函数.它保证安全吗?
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)