C++返回静态数组地址的函数

C++ function returning address of static array

本文关键字:函数 组地址 数组 返回 静态 C++      更新时间:2023-10-16

在下面的代码块中...

#include <iostream>
int* a() 
{
  static int nums[] = { 1, 2, 3 };
  return nums;
}
int* const& b() 
{
  static int nums[] = { 4, 5, 6 };
  return nums;
}
void c( int*& num )
{
  if ( num )
  {
    std::cout << "I got " << *num << std::endl;
  }
}
void d( int* const& num )
{
  if ( num )
  {
    std::cout << "I got " << *num << std::endl;
  }
}
int main( int argc, char* argv[] )
{
  int* nums = a();
  std::cout << nums[1] << std::endl;
  int* const nums2 = b();
  std::cout << nums2[1] << std::endl;
  int* num = new int(64);
  c( num );
  delete num;
  int num2 = 101;
  d( &num2 );
}

。为什么函数int* const& b()生成以下编译警告?

sh-4.2$ g++ -o main *.cpp                                                                                                                                                                                
main.cpp: In function 'int* const& b()':                                                                                                                                                                 
main.cpp:12:10: warning: returning reference to temporary [-Wreturn-local-addr]                                                                                                                          
   return nums;

我认为nums b()是静态的,因此在内存的数据部分,因此不受返回真正函数局部变量地址的问题的影响。

我尝试在我的桌面和两个在线C++编译器上编译和运行此代码。可执行文件在桌面和一个在线编译器上运行良好,但在第二个在线编译器上,它在打印"2"后提前死亡。但是我无法访问核心文件,也没有看到堆栈跟踪以查看实际出了什么问题。(工作的在线编译器是教程点,非工作的在线编译器是codechef(

我特别困惑为什么b()生成此警告和/或运行时错误,而a()不会。

发生这种情况的原因是nums不是一个指针,它是一个数组。尽管C++会根据需要将其隐式转换为指针,但获取对数组的引用并将其表示为指针将需要临时的。从本质上讲,C++将这样做:

static int nums[] = { 4, 5, 6 };
int* invisible = nums;
return invisible;

创建静态指针并引用它将修复此警告:

static int data[] = { 4, 5, 6 };
static int* nums = data;
return nums;

或者,你可以typedef一个固定长度的数组,并将其用作b()的返回类型:

typedef int array3[3];
array3 const& b()
{ 
  static int nums[] = { 4, 5, 6 };
  return nums;
}
...
array3 const &nums2 = b();