随笔-348  评论-598  文章-0  trackbacks-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 ;
}

参数带引用的话只可以改变参数的值的,也和双指针一样,但貌似传递引用更加保险,不会因为疏忽而改变了指针的指针的值
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 阅读(337) 评论(0)  编辑  收藏 所属分类: C/C++

只有注册用户登录后才能发表评论。


网站导航: