gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 01:40:33 24 4
gpt4 key购买 nike

在下面的代码块中...

#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() 会生成此警告和/或运行时错误,而 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;

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

typedef int array3[3];

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

关于C++函数返回静态数组地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43059752/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com