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;
我认为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();
相关文章:
- 如何在c++程序中找到函数的地址
- 从 C++ 中的函数返回数组地址问题
- 打印字符数组地址的正确方法
- 调用 lua 函数的地址为 C/C++?
- 为什么每次执行时函数的地址都不同?
- 获取函数的地址?
- 重载函数的地址与所需类型不匹配
- 如何在lambda本身中获取C++lambda函数的地址
- C++多态性:有没有办法找到对象成员函数的地址?
- 获取要在C++中动态调用的回调函数的地址
- 字符数组地址和整数数组地址
- 将函数的地址转换为UINTPTR_T给我不正确的结果
- 函数组的文档注释
- 在 C++ 03 中,如何引用一个被煽动的模板函数的地址
- 获取内联定义的友元函数的地址
- C++返回静态数组地址的函数
- 为什么我的函数打印地址而不是数组的内容
- 将指针数组地址传递给函数并更新地址中的数据
- 通过复制将数组地址传递给匿名函数失败
- 不了解示例中的行为 - strcpy() 和返回本地数组地址的函数