【发布时间】:2014-06-10 12:52:54
【问题描述】:
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;
}
是否保证deallocateSomething(ptr) 将释放所有分配的字节,即使它不知道调用allocateSomething<T>() 时使用的typename T?
或者是否也需要模板化deallocateSomething?
编辑:我手动处理对象的构造/销毁。
编辑 2:这会正常工作吗?
template<typename T> char* allocateSomething()
{
return reinterpret_cast<char*>(std::malloc(sizeof(T)));
}
void deallocateSomething(char* mPtr) { std::free(mPtr); }
// ...
【问题讨论】:
-
指针的值未指定,删除未指定的指针具有未定义的行为。
-
@user2079303:是什么让您认为它未指定?
char*在处理内存方面非常特别。 -
@MatthieuM,标准让我这么认为:“
reinterpret_cast执行的映射可能会或可能不会产生与原始值不同的表示。”如果标准以其他方式保证reinterpret_cast到char*不会产生不同的表示,那么我同意可以保证该值是明确定义的。 -
@VittorioRomeo:我也不太明白……
-
@VittorioRomeo,我只能推测人们对行为未定义的代码投了反对票……当问题的目的是询问代码是否正常时,这似乎不公平。
标签: c++ memory c++11 memory-management