Car*_*arl 2 c++ cookies portability memory-management
我想出了这个作为调试问题的快速解决方案 - 我有指针变量及其类型,我知道它指向堆上分配的对象数组,但我不知道有多少.所以我写了这个函数来查看存储在堆上分配内存时的字节数的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;
}
Run Code Online (Sandbox Code Playgroud)
我想知道这段代码的可移植性.