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

Dr.*_*lfe 5 c++ malloc class variable-declaration

我想要一个类共用的堆分配缓冲区(在计算过程中用作暂存器).在某些时候,我可以释放,然后重新分配缓冲区,如果它不够大.我希望缓冲区存在而不必调用"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 to 63 on 64bit machine)
   for (int i = 0; i < myclass::length; i++) {
       *(myclass::pbuf+i) = i;
   }

   // read from buffer (print the numbers 0 to 63)
   for (int i = 0; i < myclass::length; i++) {
     printf("%d\n", *(myclass::pbuf+i));
   }

   free(myclass::pbuf); // last line of program
}
Run Code Online (Sandbox Code Playgroud)

谢谢你的回答.这样的声音比我想象的更常见."在静态初始化器中允许函数调用".这导致我略微修改版本捕获可能的malloc错误:

#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
   static void* malloc_buf(unsigned int);
};

// 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);
char* myclass::pbuf = (char*)myclass::malloc_buf(sizeof(char)*myclass::length);

void* myclass::malloc_buf(unsigned int N) {
    void* buf = malloc(N);
    if (!buf) exit(EXIT_FAILURE);
    return buf;
} 

int main() {

   // write to buffer (0 to 63 on 64bit machine)
   for (int i = 0; i < myclass::length; i++) {
       *(myclass::pbuf+i) = i;
   }

   // read from buffer (print the numbers 0 to 63)
   for (int i = 0; i < myclass::length; i++) {
     printf("%d\n", *(myclass::pbuf+i));
   }

   free(myclass::pbuf); // last line of program
}
Run Code Online (Sandbox Code Playgroud)

Oli*_*ain 2

它只是进行静态初始化(在调用 main 之前进行初始化)。静态初始值设定项允许调用函数。