How do I know if an object is created on the heap or not ..?

We want to work with a system with a low latency, heap allocation in the application is more expensive. but to some extent the creation of an object on the heap is allowed. That is why we want to indicate whether an object is created on the heap or not.?

Is the following methodology the correct way to detect an object created in heap memory.?

Will have a common class in which the new and remote operator is overloaded to support heaps highlighted by 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 that we need to check to create the heap, will be obtained from the MemStat class, use the new delete and delete call when creating the 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; } 
+4
source share
1 answer

Note that your schema fails as soon as the MyClass object is a sub-object (inherited or contained) of another object that may or may not be distributed dynamically. (And the tricks I know to prevent dynamic allocation also don't work on this.)

So, what you do is this slows down the heap allocation even more without getting much. Except for a few very rare circumstances when an object is selected, this is a decision made by your class .
If they think they need to dynamically highlight one, with whom do you disagree?

+6
source

Source: https://habr.com/ru/post/1332672/


All Articles