如何在 C++ 中通过引用返回类对象?

2023-12-03C/C++开发问题
3

本文介绍了如何在 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.

这篇关于如何在 C++ 中通过引用返回类对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6