我对sizeof操作员的评估时间感到困惑.
什么时候对sizeof运算符进行求值?
它的评估时间[ compile-time or run-time] 是否取决于语言[ C? C++?]?
我们可以sizeof在运行时[ in C++] 创建的对象中使用吗?
Oli*_*rth 20
几乎在所有情况下,sizeof都是基于静态类型信息进行评估的(基本上是在编译时).
一个例外(我认为唯一的例子)就是C99的可变长度数组(VLA).
dje*_*lin 12
几乎总是编译时间.但您可能会对以下示例感兴趣:
char c[100];
sizeof(c); // 100
char* d = malloc(100);
sizeof(d); //probably 4 or 8. tells you the size of the pointer!
BaseClass* b = new DerivedClass();
sizeof(b); //probably 4 or 8 as above.
void foo(char[100] x) {
sizeof(x); //probably 4 or 8. I hate this. Don't use this style for this reason.
}
struct Foo {
char a[100];
char b[200];
};
sizeof(struct Foo); //probably 300. Technically architecture dependent but it will be
//the # of bytes the compiler needs to make a Foo.
struct Foo foo;
sizeof(foo); //same as sizeof(struct Foo)
struct Foo* fooP;
sizeof(fooP); //probably 4 or 8
class ForwardDeclaredClass;
ForwardDeclaredClass* p;
sizeof(p); //4 or 8
ForwardDeclaredClass fdc; //compile time error. Compiler
//doesn't know how many bytes to allocate
sizeof(ForwardDeclaredClass); //compile time error, same reason
Run Code Online (Sandbox Code Playgroud)