看看 C++新的[] cookie。这段代码的可移植性如何?
我想出了这个作为调试问题的快速解决方案 - 我有指针变量及其类型,我知道它指向堆上分配的对象数组,但我不知道有多少个。所以我写了这个函数来查看在堆上分配内存时存储字节数的cookie。
template< typename T >
int num_allocated_items( T *p )
{
return *((int*)p-4)/sizeof(T);
}
//test
#include <iostream>
int main( int argc, char *argv[] )
{
using std::cout; using std::endl;
typedef long double testtype;
testtype *p = new testtype[ 45 ];
//prints 45
std::cout<<"num allocated = "<<num_allocated_items<testtype>(p)<<std::endl;
delete[] p;
return 0;
}
我想知道这段代码的可移植性如何。
I came up with this as a quick solution to a debugging problem - I have the pointer variable and its type, I know it points to an array of objects allocated on the heap, but I don't know how many. So I wrote this function to look at the cookie that stores the number of bytes when memory is allocated on the heap.
template< typename T >
int num_allocated_items( T *p )
{
return *((int*)p-4)/sizeof(T);
}
//test
#include <iostream>
int main( int argc, char *argv[] )
{
using std::cout; using std::endl;
typedef long double testtype;
testtype *p = new testtype[ 45 ];
//prints 45
std::cout<<"num allocated = "<<num_allocated_items<testtype>(p)<<std::endl;
delete[] p;
return 0;
}
I'd like to know just how portable this code is.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它甚至不能远程携带。
实现可以按照需要执行堆簿记,并且绝对没有办法可移植地获取堆分配的大小,除非您自己跟踪它(这是您应该做的)。
It is not even remotely portable.
An implementation can perform heap bookkeeping however it wants and there is absolutely no way to portably get the size of a heap allocation unless you keep track of it yourself (which is what you should be doing).
您可以全局重载数组上的 new/delete 运算符,并将大小放入内存区域。您将获得一个便携式解决方案。
下面的代码显示了如何:
结果:
You can globally overload new/delete operators on array, and put the size into the memory area. You get a portable solution.
The below code shows how:
Result:
不便携。但为什么不使用 std::vector 呢?然后你可以直接询问它包含多少个元素,而无需担心内存管理和异常安全。
Not portable. But why not use
std::vector
? Then you can ask it directly how many elements it contains, and you won't need to worry about memory management and exception safety.