简体   繁体   English

要返回指向struct的指针还是将其传递?

[英]To return a pointer to struct or pass it in?

Which of these is more efficient and better code? 其中哪一个是更有效和更好的代码? or is there some other way I should be doing this? 还是我应该采取其他方法?

typedef struct foo {
int width;
int height;
} foo;

...this typedef in both the below examples, but its really an arbitrary structure... 在以下两个示例中均为typedef,但实际上是任意结构...

foo *new_foo (int width, int height) {

  foo *f
  if ((f = malloc(sizeof(foo)))==NULL) return NULL;

  f->width = width;
  f->height = height;

  return foo;
}  


void del_foo (foo *f) {free(f);}


int main () {

  int width = 3;
  int height = 4; // arbitrary values

  foo *f   
  f = new_foo(width, height)

  // do something with foo here      

  del_foo(f);
}

or 要么

int new_foo (foo *f, int width, int height) {

  f->width = width;
  f->height = height;

  return 0;
}  


int main () {

  int width = 3;
  int height = 4; // arbitrary values

  foo *f
  if ((f = malloc(sizeof(foo)))==NULL) return NULL;   
  new_foo(f, width, height)

  // do something with foo here      

  free(f);
}

Thanks! 谢谢! My apologies for any typos. 对于任何错别字,我深表歉意。

foo* new_foo(int width, int height)

seems preferable for a function with new in its name ( new will imply dynamic allocation to people with experience of C++). 对于名称为new的函数而言,似乎更可取( new将隐含动态分配给有C ++经验的人员)。

void foo_init(foo f, int width, int height)

would be reasonable if you wanted to allow clients to declare foo objects on the stack as well as heap. 如果您想允许客户端在堆栈和堆上声明foo对象,那将是合理的。 You could also choose to provide both, implementing new_foo as a malloc then a call to foo_init . 您也可以选择同时提供两者,将new_foo实现为malloc然后调用foo_init

If you provide a function which allocates memory, it'd be reasonable to also offer a function which destroys an object - foo_destroy(foo ) ( del_foo in your question?) 如果您提供分配内存的函数,则还可以提供销毁对象的函数foo_destroy(foo ) (您的问题中的del_foo ?)是合理的。

One last, minor, point - you can more obviously group related functions if you prefix their names the struct they operate on rather than adding the struct at the end (ie foo_new is more usual than new_foo ) 最后一点,要点-如果将相关函数的名称前缀为其操作的结构的前缀,而不是在末尾添加该结构,则可以更明显地对它们进行foo_new (即foo_newnew_foo更常见)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM