在下面的代码块中。
#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()
则不会。
发布于 2017-03-27 18:49:23
发生这种情况的原因是,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();
https://stackoverflow.com/questions/43059752
复制相似问题