开发者

How to know object creation is on heap or not..?

开发者 https://www.devze.com 2023-01-31 13:09 出处:网络
We want to work on low latency system, heap allocation is costlier in the application. but for some extent object creation on heap is allowed. Thats why we want indication whether object is created is

We want to work on low latency system, heap allocation is costlier in the application. but for some extent object creation on heap is allowed. Thats why we want indication whether object is created is on heap or not..?

Is the below methodology is the correct way to find out object created on heap memory..?

Will have generic class where new and delete operator is overloaded to maintain heap allocated pointers....

#include <iostream>
#include <set>

using namespace std;

class MemStat              //base class
{
    typedef set<MemStat*> POINTERS; 
    static POINTERS m_ptrlist;
public:
    void* operator new (size_t size)
    {
        MemStat* ptr = ::new MemStat;
        m_ptrlist.insert(ptr);
        return ptr;
开发者_运维问答    }
    void operator delete(void* dptr)
    {
        MemStat* ptr = static_cast<MemStat*>(dptr);
        m_ptrlist.erase(ptr);
        ::delete ptr;
    }
    // void* operator new[] (size_t sz);
    // void operator delete[] (void*);

    bool is_on_heap() { m_ptrlist.find(this) != m_ptrlist.end(); }

protected:             // ctor & dtor are protected for restrictions
    MemStat() { }
    virtual ~MemStat() { }
    MemStat(const MemStat&) { } 
    const MemStat& operator=(const MemStat& ) { return *this; }
};
MemStat::POINTERS MemStat::m_ptrlist;

for the end user classes which we need to check for the heap creation will be derived from MemStat class uses new & delete operator call while instantiating base class object.

class MyClass : public MemStat   //end user class
{
};

int main()
{
    MyClass* myptr = new MyClass;
    MyClass obj;

    cout << myptr->is_on_heap() << endl;    //results into yes
    cout << obj.is_on_heap() << endl;       //reults into no

    delete myptr;
}


Note that your scheme fails miserably as soon as a MyClass object is a sub-object (inherited or contained) of another object which might or might not by allocated dynamically. (And the tricks I know for preventing dynamic allocation fail on that one as well.)

So what you're doing just further slows down heap allocation without gaining much. Except for a few very rare circumstances, where an object is allocated is something your class' users decide.
If they think they need to dynamically allocate one, who are you to disagree?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号