2012-02-23 36 views
0

你觉得要严格使用const每个值将不会被改变的时间或通过参数为指针,只有当数据将被修改,这一点很重要?正确的参数为const或操作数

我想正确地做事,但如果作为参数传递的struct尺寸很大,难道您不想传递地址而不是复制数据吗?通常它好像刚刚宣布struct参数作为一个操作数是最具功能性。

//line1 and line2 unchanged in intersect function 
v3f intersect(const line_struct line1, const line_struct line2); 
//"right" method? Would prefer this: 
v3f intersect2(line_struct &line1, line_struct &line2); 

回答

1
v3f intersect(const line_struct line1, const line_struct line2); 

是完全等同于

v3f intersect(line_struct line1, line_struct line2); 

在外部行为而言,为各行的两个手副本intersect,所以原线不能由功能进行修改。只有当你实现(而非申报)与const形式的功能,有区别,但不是在外部行为。

这些形式不同于

v3f intersect(const line_struct *line1, const line_struct *line2); 

不具有对线条进行复制,因为它只是传递指针。这是C中的首选形式,特别是对于大型结构。它也需要opaque types

v3f intersect2(line_struct &line1, line_struct &line2); 

无效C.

+0

两个第一原型是不等价的。在第二个函数中,您可以修改函数体中的参数。 – ouah 2012-02-23 21:40:26

+0

根据编译器的不同,将const应用于按值传递参数可能有助于优化。编译器应该将const限定符解释为不允许写入参数的语句。 – Throwback1986 2012-02-23 21:45:22

+0

@ouah:你说得对,补充说他们在外部行为上是相同的。 – 2012-02-23 21:47:27

0

C没有参考(&)。

在C语言中,使用一个指向const结构的参数类型:

v3f intersect(const line_struct *line1, const line_struct *line2); 

因此,只有一个指针会在函数调用拷贝,而不是整个结构。

相关问题