質問

Is there a way to get size of a single element or element count allocated using operator new[] ?

What I mean:

void* Object::operator new[](size_t size)
{
    void *temp = ::operator new(size);

    //Get size of single element or count of elements being allocated

    return temp;
}

Why I need it:

operator new(size_t) and operator new[](size_t) are invoked only when object is allocated on heap so I've got an idea of creating c++ garbage collection based on this.

  1. All objects inherit from Object class
  2. Object class overrides operator new(size_t) and operator new[](size_t)like this:

    void* Object::operator new(size_t size)
    {
        Object& result = *static_cast<Object*>(::operator new(size));
        result.referenceCount = (int)&result;
        return &result;
    }
    
  3. Constructor of Object uses this information:

    Object::Object()
    {
        if ((void*)referenceCount != this)
        {
            referenceCount = -1; //stack object no reference counting
        }
        else
        {
            referenceCount = 1; //heap object count references
        }
    }
    
  4. Garbage Collector user referenceCount field to work with.

What I need now is to implement operator new[](size_t) to set referenceCount and that is why I need size of single element or element count. Impelenting operator new[](size_t) for every object out of the question.

Any ideas?

役に立ちましたか?

解決

This seems very Java-esque to me. Would it be simpler to simply write your program in Java? Anyone who has to maintain your C++ code in the future will appreciate it if you use idiomatic C++ to start with. For example use smart pointers to manage your memory rather than trying to implement garbage collection based on everything inheriting from Object.

I should point out that you left out "multiple inheritance is prohibited" from your list of conditions because in the presence of multiple inheritance your cast of raw, uninitialized memory to an Object* may not do the pointer adjustments it needs to to access the correct address of referenceCount.

Additionally if the memory of referenceCount happens to hold the address of a stack-based Object at construction your code will believe it to be heap-allocated and eventually result in UB when you delete a stack pointer.

But after all that if you still really really really want to do this, I think your only option is to use CRTP to automatically inject the array new operator into each child class. At least that way you don't have to write it yourself for every child.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top