假设我有10 kB的堆,并像这样混合使用C和C ++代码。
char* block1 = malloc(5*1024); //allocate 5
char* block2 = new[](4*1024); // allocate 4
Run Code Online (Sandbox Code Playgroud)
是否存在C堆和C ++堆,或者仅存在一个通用的堆?这样“新”知道堆的前5 kb已经分配了吗?
#include <iostream>
using namespace std;
class CCC {
public:
CCC() {cout<<"created "<<++count<<endl;}
~CCC(){cout<<"deleted "<<--count<<endl;}
int count=0;
};
CCC a;
CCC& create() {
return a;
}
int main () {
CCC result = create();
}
Run Code Online (Sandbox Code Playgroud)
上面的代码产生奇怪的输出。看起来析构函数被调用了 2 次,但计数没有减少。这是为什么?
created 1
deleted 0
deleted 0
Run Code Online (Sandbox Code Playgroud) 有一些 C 项目的结构充满了 ifdef(例如 WolfSSL https://github.com/wolfSSL/wolfssl/blob/bb70fee1ecff8945af8179f48e90d78ea7007c66/wolfssl/internal.h#L2792)
struct {
int filed_1;
int field_2;
#ifdef SETTING_A
int filed_b;
#endif
#ifdef SETTING_B
int field_b;
#endif
}
Run Code Online (Sandbox Code Playgroud)
原因是为了减少未使用选项的结构大小。有很多ifdef!到处!
有没有一种 C++ 方法可以摆脱这些 ifdef,保留编译器优化未使用字段的能力?也许使用模板、使用或 CRTP 继承?