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

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

问题描述

虽然这是非常方便的,我很少,如果有的话,遇到返回功能结构 S(或联盟 S)在C,无论是动态链接功能或静态定义的函数。结果
他们不是通过指针参数返回数据。

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中的一个动态的例子就是<一个href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms724381.aspx\"><$c$c>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 ++中,至少有一种叫做返回值优化,这是能够默默改变code是这样的:

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;
}

这摒弃了(可能堆叠饿了)真一个struct的价值回报。我想更妙的是这一点,不知道他们是聪明的:

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 code返回一个结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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