|
发表于 2024-12-16 16:19:33
|
显示全部楼层
#include <cstdio>
#include <string>
struct A
{
int a;
float b;
};
struct B
{
A a;
char c;
std::string str;
};
int main()
{
B tb; // const B tb; will fail to build by g++ 13.3
printf("%d, %f, %c, %llu\n", tb.a.a, tb.a.b, tb.c, tb.str.size());
const B* pb = new (std::nothrow) B;
if(nullptr != pb)
{
printf("%d, %f, %c, %llu\n", pb->a.a, pb->a.b, pb->c, pb->str.size());
delete pb;
}
}
编译器偷懒了,B tb;由于放栈上,编译器(g++)对成员就当了临时变量处理的,不给初始化。如果加const会编译失败,提示没有初始化。如果放堆上,像 const B* pb = new (std::nothrow) B;这种,就把成员给初始化成默认值。 |
|