如何在 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 指的是一个不存在的对象.您要么需要按值返回,要么返回在更广泛范围内声明的 Objectnew 到堆上.

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.

相关文章