C++中指针与C#中引用类型传递相似性
来源:互联网 发布:python 2.7.11.tgz 编辑:程序博客网 时间:2024/05/01 05:04
C++中指针与C#中引用类型非常相似,不仅体现在可以在任意传递函数中修改其指向的值,更体现在传递时,修改其指向:
改变指针指向的内存空间、改变引用类型变量指向的引用。通过以下的例子可清晰对比两者间的相似:
C++:
void func1()
{
char* p = new char[3];
memset(p , '5', 3);
func2(p);
// 结果为:655,并没有改变p指向的内存地址
std::cout << p << std::endl;
func3(p);
// 结果为:999,已经改变p指向的内存地址
std::cout << p << std::endl;
}
void func2(char* p)
{
p[0] = '6';
p = new char[3];
memset(p , '9', 3);
}void func3(char*& p)
{
p[0] = '6';
p = new char[3];
memset(p , '9', 3);
}C#:private void func1()
{
int[] arrValue = {1, 2, 3};
List<int> lstValue = new List<int>();
lstValue.AddRangle(arrValue);
func2(lstValue);
if(lstValue != null)
{
// 正常输出:5
Console.WriteLine(lstValue[0]);
}
func3(ref lstValue);
if(lstValue == null)
{
// 正常输出null
Console.WriteLine("list 引用改变,值为null");
}
}
private void func2(List<int> lstValue)
{
if(lstValue != null )
{
lstValue[0] = 5;
lstValue = null;
}
}
private void func3(ref List<int> lstValue)
{
if(lstValue != null )
{
lstValue[0] = 5;
lstValue = null;
}
}
0 0
- C++中指针与C#中引用类型传递相似性
- C#中引用传递与指针传递区别
- 图解C/C++中函数参数的值传递、指针传递与引用传递
- 图解C/C++中函数参数的值传递、指针传递与引用传递
- c中指针与引用
- C++中引用传递与指针传递区别
- C++中引用传递与指针传递区别
- C++中引用传递与指针传递区别
- c++中引用传递与指针传递的区别
- C++中引用传递与指针传递区别
- C++中引用传递与指针传递区别
- C++中引用传递与指针传递区别
- C++中引用传递与指针传递区别
- C++中引用传递与指针传递区别
- C++中引用传递与指针传递区别
- C++中引用传递与指针传递区别
- C++中引用传递与指针传递区别
- C++中引用传递与指针传递区别
- java查漏补缺(基础篇)
- 《失控》读书笔记
- 四大组件Activity
- php性能优化之设置php session多级目录(原文http://www.bewyn.com/archives/44)
- 四大组件之BroadcastReceiver
- C++中指针与C#中引用类型传递相似性
- 集合框架_Collection存储自定义对象并遍历案例
- easyui 自适应 fit属性
- Json解析,FastJson解析
- 三国佚事——巴蜀之危
- python 替换数据库中文本中特殊字符
- php 安装xdebug扩展
- javascript数据类型
- 指针作为返回值