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
原创粉丝点击