void
?fu(X
*&
?x)
{
????x
=
new
?X();
????cout
<<&
x
<<
endl;
}
int
?main()
{

????X
*
?c
=
NULL;
????
????fu(c);
????cout
<<&
c
<<
endl;
????c
->
display();


????
return
?
0
;
}
參數帶引用的話只可以改變參數的值的,也和雙指針一樣,但貌似傳遞引用更加保險,不會因為疏忽而改變了指針的指針的值
void?fu(X**?x)
{
????*x=new?X();
????cout<<*x<<endl;
}
int?main()
{

????X*?c=NULL;
????
????fu(&c);
????cout<<c<<endl;
????c->display();


????return?0;
}

Pass-by-Reference versus Pass-by-Value
Pass-by-reference is required when you want to modify the parameter and see those changes reflected
in the variable argument to the function or method However, you should not limit your use of pass-byreference
to only those cases. Pass-by-reference avoids copying the argument to the function, providing
two additional benefits in some cases:
1. Efficiency: large objects and structs could take a long time to copy. Pass-by-reference passes
only a pointer to the object or struct into the function.
2. Correctness: not all objects allow pass-by-value. Even those that do allow it might not support
deep copying correctly. As you learned in Chapter 9, objects with dynamically allocated memory
must provide a custom copy constructor in order to support deep copying.
If you want to leverage these benefits, but do not want to allow the original objects to be modified, you
can mark the parameters const. This topic is covered in detail later in this chapter.
These benefits to pass-by-reference imply that you should use pass-by-value only for simple built-in
types like int and double for which you don’t need to modify the arguments. Use pass-by-reference in
all other cases.
---------------------------------------------------------
專注移動開發
Android, Windows Mobile, iPhone, J2ME, BlackBerry, Symbian
posted on 2007-03-17 11:20
TiGERTiAN 閱讀(344)
評論(0) 編輯 收藏 所屬分類:
C/C++