sizeof(function) 有意义吗?

Does sizeof(function) makes sense?

我对 sizeof(function) 有点困惑。我曾经认为 sizeof 运算符对 class 对象、指针和引用进行操作 .

运算符 sizeof运算符可以运算什么?

sizeof(function)有意义吗?

根据:http://en.cppreference.com/w/cpp/language/sizeof

"...sizeof cannot be used with function types, incomplete types, or bit-field glvalues"

或来自 http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf 的 2012 年 C++ 标准工作草案:

Section 5.3.3 Sizeof "The sizeof operator shall not be applied to an expression that has function or incomplete type, to an enumeration type whose underlying type is not fixed before all its enumerators have been declared, to the parenthesized name of such types, or to an lvalue that designates a bit-field."

>C++中sizeof运算符可以操作哪些操作数?

来自 C++11 ISO Standerds(草案 N3337,第 105 页,第 5.3.3

The sizeof operator yields the number of bytes in the object representation of its operand. The operand is either an expression, which is an unevaluated operand (Clause 5), or a parenthesized type-id. (Clause 5 (draft N3337, page 83)))


> sizeof(function) 有意义吗?

8.5.2.3/ 部分的文档中陈述(草案 N3337,第 105 页,第 5.3.3:

  1. The sizeof operator shall not be applied to an expression that has function or incomplete type, to an enumeration type whose underlying type is not fixed before all its enumerators have been declared, to the parenthesized name of such types, or to an lvalue that designates a bit-field.
  2. The sizeof operator can be applied to a pointer to a function, but shall not be applied directly to a function.
  3. The lvalue-to-rvalue , array-to-pointer , and function-to-pointer standard conversions are not applied to the operand of sizeof.
  4. sizeof(char), sizeof(signed char) and sizeof(unsigned char) are 1. The result of sizeof applied to any other fundamental type (3.9.1) is implementation-defined.

尽管 Avi Weiss 和 JeJo 的回答中正确指出 sizeof(func) 是无效的,但如果您尝试它,则不一定会出错。

在 GNU C 中,sizeof(void)sizeof(func) 被允许作为扩展并计算为 1。 This is a documented extension. 根据标准的要求,你会得到一个警告,但是不是错误。此扩展在 C++ 模式下也可用。