1

我找不到有关 sizeof 行为的信息(至少在 gcc 4.6+ 中)。以下代码有效并产生“预期”结果(4、1、8),但我想知道为什么。我检查了几个问题,但没有一个显示像这样的例子。

#include<iostream>

int f1(int) {
  return 0;
}

char f2(char) {
  return 0;
}

double f3() {
  return 0;
}

int main() {
  std::cout << sizeof(f1(0)) << std::endl;
  std::cout << sizeof(f2('0')) << std::endl;
  std::cout << sizeof(f3()) << std::endl;

  return 0;
}

一个答案将不胜感激。谢谢。

4

4 回答 4

4

运算符可以将sizeof类型或表达式作为参数并返回其参数的大小。您正在使用表达式,因此它返回这些表达式的大小。表达式不会在运行时求值——所以函数永远不会被调用。但是正确的(重载)函数用于确定结果的大小。

在(现已删除的)评论中,user1919074说:

sizeof(f1)行不通

脑放屁

在 C 中,sizeof(f1)可以工作,因为它会返回指向函数的指针的大小。

sizeof()运算符不能直接应用于函数名称。它有特殊的规则,当应用于数组时,指针的正常“衰减”不会发生。同样,将函数名更改为函数指针也不会发生在sizeof(). (当然,你必须用力戳 GCC-pedantic才能让它发出警告/错误;否则,它返回 1 作为函数的大小。)

于 2013-05-10T14:33:40.843 回答
2

函数中发生了什么

int f1(int) {
  return int(0);
}

char f1(char) {
  return char(0);
}

double f1() {
  return double(0);
}

以后会发生什么。

std::cout << sizeof(int(0)) << std::endl;
std::cout << sizeof(char('0')) << std::endl;
std::cout << sizeof(double(0)) << std::endl;

因为您正在打印从函数返回sizeofvalue内容

于 2013-05-10T14:35:37.673 回答
1

ISO/IEC 14882 on C++ says (section 5.3.3 - page 79): says

"The size operator shall not be applied to an expression that has function or incomplete type,..."

Also notice the compilation warning with the -pedantic option enabled...

warning: invalid application of 'sizeof' to a function type
于 2013-05-10T15:04:47.817 回答
0

f1 返回一个占用 4 个字节的整数。
f2 返回一个占 1 个字节的字符。
f3 返回一个占用 8 个字节的双精度数。

所以 sizeof() 所做的只是返回其参数的大小。

于 2013-05-10T14:43:11.790 回答