C++引用和指针的坑

712 阅读1分钟

1.循环体中的结构体指针

循环体内的结构体指针如果不使用new创建的话,永远是只有一个指针,每个指针的地址都一样。而且new只能创建结构体指针,不能用于创建结构体本身。

#include<iostream>
using namespace std;
struct ptrhole
{
    int hole;        
};

int main(){
    for (int i = 0; i < 3; i++)
    {
        ptrhole holes={i};
        cout<<&holes<<" ";
    }
    return 0;
}

//output:0x7fffaf92cf48 0x7fffaf92cf48 0x7fffaf92cf48 
#include<iostream>
using namespace std;
struct ptrhole
{
    int hole;        
};

int main(){
    for (int i = 0; i < 3; i++)
    {
        ptrhole* holes=new ptrhole;
		holes->hole=i;
        cout<<&holes<<" ";
    }
    return 0;
}
#include<iostream>
using namespace std;
struct ptrhole
{
    int hole;        
};

int main(){
    for (int i = 0; i < 3; i++)
    {
        ptrhole* holes=new ptrhole;
		holes->hole=i;
        cout<<"outer"<<holes<<"\n";
    }
    return 0;
}
//output:
outer0x23c54ba2490
outer0x23c54a15fa0
outer0x23c54ba27d0

2.指针的形参和实参

当内部函数想要改变外部的函数的某些参数的时候,可以使用传入该参数指针的方式,但是内部函数的返回不是该该参数,不要使用这种方式,应该使用引用传递。

#include<iostream>
using namespace std;
struct ptrhole
{
    int hole;        
};

void getptr(ptrhole* holes){
    cout<<"inner"<<&holes<<"\n";
}

int main(){
    for (int i = 0; i < 3; i++)
    {
        ptrhole* holes=new ptrhole;
		holes->hole=i;
        cout<<"outer"<<holes<<"\n";
        getptr(holes);
    }
    return 0;
}
//output:
outer0x23c54ba2490
inner0xb40d9ff9e0
outer0x23c54a15fa0
inner0xb40d9ff9e0
outer0x23c54ba27d0
inner0xb40d9ff9e0

发现如果这样的话,内外指针的值不一致,除非该函数的返回了这个参数,才会拿到一个完整的映射,才能改变外面的函数的参数

#include<iostream>
using namespace std;
struct ptrhole
{
    int hole;        
};

void getptr(ptrhole* holes){
    cout<<"inner"<<&holes<<"\n";
}
ptrhole* returnhole(ptrhole* holes){
    holes->hole++;
    return holes;
}

int main(){
    for (int i = 0; i < 3; i++)
    {
        ptrhole* holes=new ptrhole;
		holes->hole=i;
        cout<<"outer"<<holes<<"\n";
        returnhole(holes);
        cout<<"hole'snumber"<<holes->hole<<"\n";
    }
    return 0;
}
//output:
outer0x1f698e22490
hole'snumber1
outer0x1f698ce5fa0
hole'snumber2
outer0x1f698e227d0
hole'snumber3

最好的方式还是引用传递

#include<iostream>
using namespace std;
struct ptrhole
{
    int hole;        
};

void getptr(ptrhole &holes){
    cout<<"inner"<<&holes<<"\n";
}
int main(){
    for (int i = 0; i < 3; i++)
    {
        ptrhole holes=new ptrhole;
		holes->hole=i;
        cout<<"outer"<<holes<<"\n";
    }
    return 0;
}