我有一个 placement new 运算符,完全可以预见,它会从池中分配内存。但是,我还需要知道对象类型才能设置一些元字段。我可以将它作为第二个参数作为字符串传递给 placement new,但是由于我在调用 new 时指定了类型,所以没有任何方法可以隐式获取它吗?
例如我可以这样做:
void* operator new(size_t count, Pool* pool, const char* type)
{
return pool->alloc(count, type); // type is used to associate metadata with the allocated chunk
}
Car* car = new(pool, "Car") Car(...);
但是我不能做这样的事情吗?
template<class T>
void* operator new(size_t count, Pool* pool)
{
return pool->alloc(count, typeid(T).name());
}
Car* car = new(pool) Car(...);
最佳答案
不,对不起。除了仅适用于您控制的类类型的成员分配器函数外,C++ 既不使用类类型来选择 operator new
函数,也不为 operator new
提供任何标准方法函数以确定调用 new 表达式的类型(如果有的话)。
你可以给你的Pool
类一个模板成员函数来处理分配和构造:
template<typename T, typename... Args>
T* Pool::create(Args&& ... args) {
void* ptr = alloc(count, typeid(T).name());
try {
return ::new(ptr) T(std::forward<Args>(args)...);
} catch (...) {
dealloc(ptr);
throw;
}
}
// ...
Car* car = pool->create<Car>(vroom);
(关于您可能已经知道的东西的其他评论:记住要实现匹配的放置删除,以防类构造函数抛出异常。考虑制作一个 Allocator 接口(interface)以与标准库兼容。)
关于c++ - 在 placement new 中输入信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23438162/