如何确定 c++ 的内存运行时的对象
我试图在运行时确定对象的大小。 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
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.
您需要以某种方式自己跟踪它。例如:
请注意,您应该使用智能指针容器来管理动态分配的对象,这样您就不必手动管理它们的生命周期。在这里,我演示了
scoped_array
的使用,这是一个非常有用的容器。您还可以将shared_array
或shared_ptr
与自定义删除器一起使用。You need to keep track of it yourself somehow. For example:
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 useshared_array
or useshared_ptr
with a custom deleter.在您的系统上,对象的大小为 4 字节。然而,该对象使用额外的资源,例如 1GB 内存。
The size of the object is 4 bytes on your system. The object, however, uses additional resources, such as 1GB of memory.