*&vs&in将变量传递给函数

我试图理解C ++中的引用和指针,而我偶然发现了

#include<iostream> 
using namespace std; 

void swap(char * &str1,char * &str2) 
{ 
char *temp = str1; 
str1 = str2; 
str2 = temp; 
} 

int main() 
{ 
const char *str1 = "GEEKS"; 
const char *str2 = "FOR GEEKS"; 
swap(str1,str2); 
cout<<"str1 is "<<str1<<endl; 
cout<<"str2 is "<<str2<<endl; 
return 0; 
} 

函数Swap中的*&是什么,并与我了解的&(通过引用传递)进行比较,性能上有什么不同,或者它们如何工作,我应该使用什么?

void swap(char &str1,char &str2) 
{ 
char temp = str1; 
str1 = str2; 
str2 = temp; 
} 
zhaojiewww 回答:*&vs&in将变量传递给函数

它是对指针的引用。这样,函数不仅可以访问指针指向的内容,还可以修改传入的指针本身(它可以更改传入的指针指向的内容,因此它指向其他对象)。

,

如果将对整数的引用传递给交换函数,您将像这样将一个变量的数据复制到另一个变量:

void swap(int &a,int &b) 
{ 
    int temp = a; 
    a = b; 
    b = temp;
} 

int main() 
{ 
    int a = 1; 
    int b = 5; 
    std::cout<<"a's adress before swap: "<< &a <<'\n'; 
    std::cout<<"b's adress before swap: "<< &b <<'\n'; 
    swap(a,b); 
    std::cout<<"a's adress after swap: "<< &a <<'\n'; 
    std::cout<<"b's adress after swap: "<< &b <<'\n'; 
    return 0; 
} 

输出为:

a's adress before swap: 0x7ffeeccaba68
b's adress before swap: 0x7ffeeccaba64
a's adress after swap: 0x7ffeeccaba68
b's adress after swap: 0x7ffeeccaba64

因此它将a’s数据复制到temp,然后将b’s数据复制到a,最后将temp’s数据复制到b。如果您要传递整数之类的小对象也可以,但是如果您传递诸如Class对象之类的大对象来交换功能,则可能会花费大量的时间和空间。

另一方面,如果将对指针的引用传递给交换函数,则将仅在指针指向的位置进行调整。例如:

#include <iostream>
void swap(int *&a,int *&b){
    int *temp = a;
    a = b;
    b = temp;
}

int main(){
    int x = 1;
    int y = 5;
    int *a = &x;
    int *b = &y;
    std::cout << "where a points before swap: " << a << '\n';
    std::cout << "where b points before swap: "<< b << '\n';
    swap(a,b);
    std::cout << "where a points after swap: " << a << '\n';
    std::cout << "where b points after swap: "<< b << '\n';
    return 0;
}

请注意,在输出中,ab指向swap之后的机会:

where a points before swap: 0x7ffee1738a68
where b points before swap: 0x7ffee1738a64
where a points after swap: 0x7ffee1738a64
where b points after swap: 0x7ffee1738a68

在交换功能中,首先temp指向a(指向x)指向的位置,然后a指向b(指向{{1} })指向,最后y指向b指向(指向temp)。因此,它只是交换了指针指向的位置,而没有复制任何重要数据。因此,如果需要交换大数据对象,则指向指针的时间和空间更好。

本文链接:https://www.f2er.com/2744323.html

大家都在问