在C++裡函式參數使用pass-by-value的話,會造成參數的傳遞成本增加,所以在C++應用程式或是component開發上比較少使用pass-by-value。
在Google C++ Style Guide裡有提到Google內部使用C++ coding的規則,從裡面也可以看到Google的rule為所有函式的參數必須是pass-by-reference,並且加上cosnt,表示傳入的參數是不可以變動的,這時你可能會有個疑問,如果函式的實作需要修改到傳入的參數怎麼辦,當然這應該是很常見的case,所以他們對於有需要更改操作的arguments,可以使用pass-by-point的方式。
All parameters passed by reference must be labeled
const
.Definition:
In C, if a function needs to modify a variable, the parameter must use a pointer, eg
int foo(int *pval)
. In C++, the function can alternatively declare a reference parameter: int foo(int &val)
. Pros:Defining a parameter as reference avoids ugly code like
(*pval)++
. Necessary for some applications like copy constructors. Makes it clear, unlike with pointers, that a null pointer is not a possible value. Cons:References can be confusing, as they have value syntax but pointer semantics.
Decision:
Within function parameter lists all references must be const
:void Foo(const string &in, string *out);
const
references while output arguments are pointers. Input parameters may be const
pointers, but we never allow non-const
reference parameters.However, there are some instances where using
const T*
is preferable to const T&
for input parameters. For example:- You want to pass in a null pointer.
- The function saves a pointer or reference to the input.
const T&
. Using const T*
instead communicates to the reader that the input is somehow treated differently. So if you choose const T*
rather than const T&
, do so for a concrete reason; otherwise it will likely confuse readers by making them look for an explanation that doesn't exist.底下是在每個使用C++為開發語言的RD應該都要讀到的Effective C++裡提到的部分,
class Person{ public: Person(); ~Person(); private: string name; string address; }; class Student: public Person { public: Student(); ~Student(); private: string schoolName; string schoolAddress; };
若使用
bool validateStudent(Student s);
Student plato;
bool platoIsOK = validateStudent(plato);
Student裡有兩個string物件,每次建構一個Student物件,就會建構兩個string物件,而每次建購Student時也會建構一個Person物件,一個Person物件又會建構兩個string物件。
by value參數的傳遞成本: 一次Student的copy建構式 + 一次Person的copy建構式 + 四個string的建構,所以總共是「六次建構式 + 六次解構式」
|
- 儘量以pass-by-reference-to-const取代pass-by-value,前者比較高效,並可避免切割問題。
- 此規則不適用於內建型別,以及STL的迭代器和函式物件。對它們而言pass-by-value往往比較適當。
全站熱搜
留言列表