为什么 C 代码不返回结构? [英] Why doesn't C code return a struct?

查看:15
本文介绍了为什么 C 代码不返回结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然它非常方便,但我很少遇到在 C 中返回 structs(或 unions)的函数,无论它们是动态链接函数或静态定义的函数.
他们改为通过指针参数返回数据.

While it's very handy, I very rarely, if ever, come across functions that return structs (or unions) in C, whether they are dynamically linked functions or statically defined functions.
They instead return the data through a pointer parameter.

(Windows 中的一个动态示例是 GetSystemInfo.)

(An dynamic example in Windows is GetSystemInfo.)

这背后的原因是什么?
是因为性能问题、ABI 兼容性问题还是其他原因?

What's the reason behind this?
Is it because of a performance issue, an ABI compatibility issue, or something else?

推荐答案

我会说性能",再加上它有时甚至可能让 C 程序员感到惊讶.对许多人来说,在 C 的一般风格"中,将诸如结构之类的大东西当作仅仅是值来扔掉并不是....根据语言,它们确实是.

I would say "performance", plus the fact that it's even possible sometimes seems to surprise C programmers. It's not ... in the general "flavor" of C, to many, to throw around large things such as structs as if they were mere values. Which, according to the language, they really are.

同样,当需要复制结构时,许多 C 程序员似乎会自动求助于 memcpy(),而不仅仅是使用赋值.

Along the same lines, many C programmers seem to automatically resort to memcpy() when the need to copy structs arises, rather than just using assignment, too.

至少在 C++ 中,有一种叫做返回值优化"的东西,它能够像这样默默地转换代码:

In C++ at least, there is something called "return value optimization" which is able to silently transform code like this:

struct Point { int x, y; };

struct Point point_new(int x, int y)
{
  struct Point p;
  p.x = x;
  p.y = y;
  return p;
}

进入:

void point_new(struct Point *return_value, int x, int y)
{
  struct Point p;
  p.x = x;
  p.y = y;
  *return_value = p;
}

它消除了结构值的(可能是堆栈饥渴的)真实"返回.我想更好的是这个,不确定他们是否那么聪明:

which does away with the (potentially stack-hungry) "true" return of a struct value. I guess even better would be this, not sure if they're that smart:

void point_new(struct Point *return_value, int x, int y)
{
  return_value->x = x;
  return_value->y = y;
}

我不确定 C 编译器是否可以做到这一点,如果他们不能,那么我猜这可能是反对结构返回的真正论据,对于性能非常关键的程序.

I'm not sure if C compilers can do any of this, if they can't then I guess that might be a real argument against struct returns, for very performance-critical programs.

这篇关于为什么 C 代码不返回结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆