2012-02-23 33 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); 

因此,只有一個指針會在函數調用拷貝,而不是整個結構。

相關問題