Is there a way to determine what type of memory is used by an instance of an object?

If I have this code:

#include <assert.h>

class Foo {
public:
    bool is_static();
    bool is_stack();
    bool is_dynamic();
};

Foo a;

int main()
{
    Foo b;
    Foo* c = new Foo;

    assert( a.is_static()  && !a.is_stack()  && !a.is_dynamic());
    assert(!b.is_static()  &&  b.is_stack()  && !b.is_dynamic());
    assert(!c->is_static() && !c->is_stack() &&  c->is_dynamic());

    delete c;
}

Is it possible to implement a method is_stack, is_static, is_dynamicto perform assertions?

Usage example: counting the size of memory that certain objects of type Foo use on the stack, but not counting static or dynamic memory

+3
source share
3 answers

This cannot be done using standard C ++ tools that make efforts to make objects work the same regardless of how they are distributed.

, , . ( uintptr_t , .)

+6
+1

, . :

  • . , ,

  • , , , , . a isStatic .

  • /delete . , isDynamic .

  • ( static, ), ( ), , , , . , , .

Therefore, most of your problems are resolved during compilation, and frankly, you rarely care about them. And the rest (dynamic memory allocation) are handled differently. But if you insist on using these methods, you can tell the linker to create a map file that will provide you with address ranges for all sections of the data and use them for your purposes.

+1
source

All Articles