简体   繁体   中英

How to determine the memory of a c++ object at runtime

I'm trying to determine the size of an object at runtime. sizeof doesn't work because this returns the size at compile time. Here is an example of what I mean:

class Foo 
{
public:
    Foo() 
    {
        c = new char[1024*1024*1024];
    }
    ~Foo() 
    { 
        delete[] c; 
    }

private:
    char *c;
};

In this case, sizeof(Foo) will be 4 bytes and not ~1GB. How can I determine the size of Foo at runtime? Thanks in advance.

You need to keep track of it yourself somehow. For example:

struct Foo 
{
    Foo()
        : elements(1024 * 1024 * 1024) 
    {
        c.reset(new char[elements]);
    }

    boost::scoped_array<char> c;
    int elements;
};

Note that you should use a smart pointer container for managing dynamically allocated objects so that you don't have to manage their lifetimes manually. Here, I've demonstrated use of scoped_array , which is a very helpful container. You can also use shared_array or use shared_ptr with a custom deleter.

The size of Foo is constant. The ~1GB of chars does not technically belong to the object, just the pointer to it does. The chars are only said to be owned by the object, because the object is responsible for allocating and deallocating memory for them. C++ does not provide features that allow you to find out how much memory an object has allocated. You have to keep track of that yourself.

The size of the object is 4 bytes on your system. The object, however, uses additional resources, such as 1GB of memory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM