问题描述
我有一个名为 Object 的类,用于存储一些数据.
I have a class called Object which stores some data.
我想使用这样的函数通过引用返回它:
I would like to return it by reference using a function like this:
Object& return_Object();
然后,在我的代码中,我会这样称呼它:
Then, in my code, I would call it like this:
Object myObject = return_Object();
我已经编写了这样的代码并且它可以编译.但是,当我运行代码时,我始终遇到段错误.通过引用返回类对象的正确方法是什么?
I have written code like this and it compiles. However, when I run the code, I consistently get a seg fault. What is the proper way to return a class object by reference?
推荐答案
您可能正在返回堆栈上的对象.也就是说,return_Object() 可能看起来像这样:
You're probably returning an object that's on the stack. That is, return_Object() probably looks like this:
Object& return_Object()
{
Object object_to_return;
// ... do stuff ...
return object_to_return;
}
如果这是你正在做的事情,那你就不走运了 - object_to_return 已经超出范围并在 return_Object 的末尾被破坏,所以 myObject 指的是一个不存在的对象.您要么需要按值返回,要么返回在更广泛范围内声明的 Object 或 new 到堆上.
If this is what you're doing, you're out of luck - object_to_return has gone out of scope and been destructed at the end of return_Object, so myObject refers to a non-existent object. You either need to return by value, or return an Object declared in a wider scope or newed onto the heap.
这篇关于如何在 C++ 中通过引用返回类对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)