【问题标题】:Proper arguments as const or operands正确的参数作为 const 或操作数
【发布时间】:2012-02-23 21:33:49
【问题描述】:

您认为每次值不会更改时严格使用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); 

【问题讨论】:

    标签: c struct arguments constants operands


    【解决方案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。

    【讨论】:

    • 前两个原型不等价。在第二个函数中,您可以修改函数体中的参数。
    • 取决于编译器,将 const 应用于按值传递参数可能有助于优化。编译器应将 const 限定符解释为不允许对参数进行写入的语句。
    • @ouah:你说得对,补充说它们在外部行为上是等价的。
    【解决方案2】:

    C 没有引用 (&)。

    在 C 中,使用指向 const 结构的指针作为参数类型:

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

    所以在函数调用中只会复制一个指针,而不是整个结构。

    【讨论】:

      猜你喜欢
      • 2015-10-02
      • 1970-01-01
      • 1970-01-01
      • 2019-12-28
      • 2020-12-13
      • 1970-01-01
      • 2014-06-28
      • 2018-09-02
      • 1970-01-01
      相关资源
      最近更新 更多