c++ - 在 placement new 中输入信息

标签 c++

我有一个 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/

相关文章:

C++ 到 pep/8 汇编语言帮助(链接数据结构)

c++ - c_str == string 与 c_str == c_str 的值相等

c++ - C++中的局部变量问题

c++ - 在回溯中使用 `free()` 解除分配时出现 `delete` 错误

c++ - OpenGL渲染器类设计: flexible and simple?

c++ - 如何在不复制的情况下稳定排序?

java - 如何将 Java 对象转换为 C++ 对象?

c++ - C++ 中的简单多线程服务器?

c++ - C++中的结构继承

c++ - 在发生某些其他初始化后,如何初始化类的静态成员?