我对运算符sizeof
的评估时间感到困惑。
sizeof运算符什么时候被评估?sizeof运算符编译时或运行时间
其评估时间[compile-time or run-time
]取决于语言[C? C++?
]?
如果在运行时创建对象[in C++
],我们可以使用sizeof
吗?
我对运算符sizeof
的评估时间感到困惑。
sizeof运算符什么时候被评估?sizeof运算符编译时或运行时间
其评估时间[compile-time or run-time
]取决于语言[C? C++?
]?
如果在运行时创建对象[in C++
],我们可以使用sizeof
吗?
在几乎所有情况下,sizeof
都是基于静态类型信息(在编译时,基本上)进行评估。
一个例外(我认为唯一的例外)就是C99的可变长度数组(VLA)。
几乎总是编译时间。但是,下面的例子可能是你的兴趣:
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
也许“void foo(char [100] x)”实际上应该是“void foo(char x [100])”? –
编译时间,因为它是在编译时计算出的大小“编译时间”,当你建立你的代码 - 当编译器的源代码转换成IL。
一个很好的证明什么是一个荒谬的变态VLAs。恕我直言,显式可变长度堆栈消耗('alloca')非常好。 – valdo
@valdo,我不明白这应该证明什么。在执行时间动态调整大小的对象时,必须在执行时对其进行评估,这似乎很正常。并且比较其他机制,比如'alloca'(甚至没有标准化并且没有范围界定)或者'malloc',它们都不知道它们创建的对象的大小并不是很有帮助。 –
@Jens Gustedt:对不起,我的意思是* example *,而不是* proof *。 'alloca'不需要显式的释放/范围。生成的代码(或多或少)与VLA相同 - 移动堆栈指针+在页面边界交叉时探测堆栈内存。我个人在元编程(temapltes等)中非常积极地使用'sizeof',并且我想100%确定'sizeof'里面的任何内容都不会在运行时被评估。 – valdo