您的位置:首页 > 编程语言 > C语言/C++

C++指针的指针和指针的引用

2017-06-07 00:00 155 查看
摘要: C++内存分配

分析如下代码:

#include <iostream>

using namespace std;

//指针
void func1(int *ptr)
{
ptr = new int(10);
}

//指针的指针
void func2(int **ptr)
{
*ptr = new int(20);
}

//指针的引用
void func3(int *&ptr)
{
ptr = new int(30);
}

int main(int argc, char *argv[])
{
int val1 = 5;
int val2 = 5;
int val3 = 5;
int* ptr1 = &val1;
int* ptr2 = &val2;
int* ptr3 = &val3;
cout << *ptr1 << endl;
cout << *ptr2 << endl;
cout << *ptr3 << endl;
cout << endl;

func1(ptr1);
func2(&ptr2);
func3(ptr3);
cout << *ptr1 << endl;
cout << *ptr2 << endl;
cout << *ptr3 << endl;

return 0;
}

输出结果:

Debugging starts
5
5
5

5
20
30
Debugging has finished

第一种情况下我们是无法获取到新分配的内存数据,而且还会导致内存泄漏,最后ptr1的内容并未改变;

第二种和第三种情况下都可以获取到新分配的内存数据,不同之处在于第二种func2()中*ptr是一个指针,而在第三种情况下,*ptr是一个指针的引用。他们的区别可以参考指针和引用的区别来看待。在函数调用上也有所不同,func2(&ptr2)和func3(ptr3),这个时候func2(nullptr)是被编译允许的,而func3(nullptr)就会编译报错:invalid initialization of non-const reference of type 'int*&' from an rvalue of type 'int*'
func3(nullptr);,因此在我们需要传递的参数不能为nullptr时采用第三种方法较好。
^
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息