C++函数返回静态数组地址
C++ function returning address of static array
在下面的代码块中...
#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;
我认为 b()
中的 nums
是静态的,因此在内存的数据部分,因此不受返回真正函数局部变量地址的问题影响。
我尝试在桌面和两个在线 C++ 编译器上编译和 运行 这段代码。可执行文件在桌面和一个在线编译器上运行良好,但在第二个在线编译器上,它在打印“2”后过早死亡。但是我无权访问核心文件,也没有看到堆栈跟踪以查看实际出了什么问题。 (可用的在线编译器是 tutorialspoint,不能用的在线编译器是 codechef)
我特别困惑为什么 b()
会生成此警告 and/or 运行时错误,而 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()
的 return 类型:
typedef int array3[3];
array3 const& b()
{
static int nums[] = { 4, 5, 6 };
return nums;
}
...
array3 const &nums2 = b();
在下面的代码块中...
#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;
我认为 b()
中的 nums
是静态的,因此在内存的数据部分,因此不受返回真正函数局部变量地址的问题影响。
我尝试在桌面和两个在线 C++ 编译器上编译和 运行 这段代码。可执行文件在桌面和一个在线编译器上运行良好,但在第二个在线编译器上,它在打印“2”后过早死亡。但是我无权访问核心文件,也没有看到堆栈跟踪以查看实际出了什么问题。 (可用的在线编译器是 tutorialspoint,不能用的在线编译器是 codechef)
我特别困惑为什么 b()
会生成此警告 and/or 运行时错误,而 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()
的 return 类型:
typedef int array3[3];
array3 const& b()
{
static int nums[] = { 4, 5, 6 };
return nums;
}
...
array3 const &nums2 = b();