小编Dr.*_*lfe的帖子

main()或任何其他功能(即全球范围)之外的Malloc

我想要一个类共用的堆分配缓冲区(在计算过程中用作暂存器).在某些时候,我可以释放,然后重新分配缓冲区,如果它不够大.我希望缓冲区存在而不必调用"myclass :: initialize();" 在main(); 我想出了下面的代码,它编译并适用于我的目的.

我的问题是:为什么这段代码编译正确?为什么malloc()允许在main()或任何其他函数之外?编译器是否以某种方式解释了这个并删除了malloc?

使用"g ++ example.cpp"在linux 64bit上编译的代码,并使用valgrind进行检查

// example.cpp
#include <cstdio>
#include <cstdlib>

class myclass {
public:
   static char* pbuf;                     // buffer
   static unsigned int length;            // buffer length
   const static unsigned int chunk_size;  // allocation chunck size
};

// set constants and allocate buffer
const unsigned int myclass::chunk_size = sizeof(long unsigned int) * 8; 
unsigned int myclass::length = chunk_size;  // start with smallest chunk
char* myclass::pbuf = (char*)malloc(sizeof(char)*myclass::length);

int main() {

   // write to buffer (0 …
Run Code Online (Sandbox Code Playgroud)

c++ malloc class variable-declaration

5
推荐指数
1
解决办法
218
查看次数

标签 统计

c++ ×1

class ×1

malloc ×1

variable-declaration ×1