不小心我忘记从函数返回值,但是当我在函数声明中返回引用时,它起作用了.为什么
Accidently I forgot to return value from function but when I returned reference in function declaration it worked.Why?
#include <iostream>
#include<stdlib.h>
using namespace std;
class test{
public:
test(int a):i(a){
}
int display();
private:
int i;
};
int test::display(){
i;
}
int main() {
test obj(10);
cout<<obj.display();
return 0;
}
在上面的情况下,打印了一些随机值。但是当我将函数声明更改为:
int& display();
和定义为:
int& test::display(){
i;
}
它显示正确的值,即 10我不知道为什么?
这是未定义的行为,因此一切皆有可能 - 包括代码按预期"工作"的可能性。编译器应该已就此发出警告 - 请务必将此类警告视为错误,并在测试代码之前修复所有报告的问题。
编译器使用堆栈或 CPU 寄存器从函数返回值。当缺少return
时,返回值的空间中不会放置任何数据。但是,您计划返回的数据可能已经在寄存器中或堆栈中的正确位置,因此调用代码表现出您期望的行为。不过,它仍然没有定义。
相关文章:
- 区分接受常量参数的函数引用/指针和与函数参数同名的非常量参数
- 类 Referention 中C++回调函数引用非静态函数
- 使用函数引用指向节点的指针删除链表中的节点?
- 解释通过从函数引用返回数组的语法
- "Class1"类"Class2"对象作为私有数据成员。如何通过"Class 2"函数引用"Class1"对象?
- 使用默认构造函数引用成员变量初始化错误
- 无法调用函数引用 c++
- 使用 decltype(this) 获取函数引用
- 我应该如何定义返回指针的函数?(引用指针与指针指针)
- 从内联函数引用文件静态变量
- Boost::将sigaction函数引用绑定到实例
- 一种比函数引用更有效的方法
- 奇怪的未定义函数引用,函数调用C++不存在
- 是否可以检测绑定成员函数引用的对象是否被删除或销毁
- 构造函数引用参数导致seg错误
- 是否可以使函数模板从函数引用中获取“decltype”
- 无法让 Lua 函数引用"self"
- 如何解析变量和函数引用(Linker & Compiler)?
- 从不同模块调用函数 - 引用错误
- 如何在主函数中连接到数据库,然后从其他函数引用它