您认为每次不更改值时严格使用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);
答案 0 :(得分: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.
答案 1 :(得分:0)
C没有参考(&)。
在C中,使用指向const
结构的指针作为参数类型:
v3f intersect(const line_struct *line1, const line_struct *line2);
因此,只有一个指针将被复制到函数调用中而不是整个结构中。