在构造函数之前初始化值

Initialization of values before constructor

问题: 我为我的 class.

实现了这个新的运算符
void* Objects::MemoryObject::operator new(size_t size, Memory::BaseAllocator* allocator) {
    Objects::MemoryObject* newObject = static_cast<Objects::MemoryObject*>(allocator->allocateItem(size));
    
    newObject->_objectAllocator = allocator;
    newObject->_objectSize      = size;

    return newObject;
}

它将为对象分配内存并设置对象大小和分配中使用的分配器的属性。问题是这些值将被构造函数删除(对象大小将为 0,指向分配器的指针将为 NULL)even 如果我不在代码中初始化它们。如何避免这种情况?有没有办法告诉编译器这些属性在构造函数之前初始化?

我尝试了什么:我尝试使用 volatile 限定符但它不起作用

我认为,您不应该为您的任务使用 ordinal new。使用类似“结构”的东西:特定功能,它分配内存,创建实例并填充其他值。

唯一有效的方法是添加一种保存信息的结构。这些信息稍后由构造函数使用。此结构在代码文件 (.cpp) 中定义,因此它对程序中的其他对象不可见。

// Here we will save our values
struct {
    Memory::BaseAllocator*  allocator;
    Memory::SystemInt       size;
} MemoryObjectValues;

// we will take values from struct save them in attributes
Objects::MemoryObject::MemoryObject() {
    this->_objectAllocator  = MemoryObjectValues.allocator;
    this->_objectSize       = MemoryObjectValues.size;

    MemoryObjectValues.allocator    = nullptr;
    MemoryObjectValues.size         = 0;
}

// during allocation we will save values into struct 
void* Objects::MemoryObject::operator new(size_t size, Memory::BaseAllocator* allocator) {
    Objects::MemoryObject* newObject = static_cast<Objects::MemoryObject*>(allocator->allocateItem(size));
    // set important values like size and pointer to allocator
    MemoryObjectValues.allocator    = allocator;
    MemoryObjectValues.size         = size;
    
    return newObject;
}