How to return a class object by reference in C++?(如何在 C++ 中通过引用返回类对象?)
问题描述
我有一个名为 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 new
ed onto the heap.
这篇关于如何在 C++ 中通过引用返回类对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 C++ 中通过引用返回类对象?


- 如何对自定义类的向量使用std::find()? 2022-11-07
- 近似搜索的工作原理 2021-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 从python回调到c++的选项 2022-11-16
- Stroustrup 的 Simple_window.h 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 静态初始化顺序失败 2022-01-01
- C++ 协变模板 2021-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01