如何确定 c++ 的内存运行时的对象

发布于 2024-10-08 13:47:30 字数 321 浏览 5 评论 0原文

我试图在运行时确定对象的大小。 sizeof 不起作用,因为它返回编译时的大小。下面是我的意思的一个例子:

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

private:
    char *c;
};

在这种情况下,sizeof(Foo) 将是 4 个字节,而不是 ~1GB。如何在运行时确定 Foo 的大小?提前致谢。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

ζ澈沫 2024-10-15 13:47:30

Foo 的大小是恒定的。从技术上讲,大约 1GB 的字符并不属于该对象,只是指向它的指针属于该对象。这些字符仅被认为由该对象拥有,因为该对象负责为它们分配和释放内存。 C++ 不提供让您了解对象分配了多少内存的功能。你必须自己跟踪这一点。

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.

笔落惊风雨 2024-10-15 13:47:30

您需要以某种方式自己跟踪它。例如:

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

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

请注意,您应该使用智能指针容器来管理动态分配的对象,这样您就不必手动管理它们的生命周期。在这里,我演示了 scoped_array 的使用,这是一个非常有用的容器。您还可以将 shared_arrayshared_ptr 与自定义删除器一起使用。

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.

画中仙 2024-10-15 13:47:30

在您的系统上,对象的大小 4 字节。然而,该对象使用额外的资源,例如 1GB 内存。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文