如何在C ++中通过引用返回类对象? [英] How to return a class object by reference in C++?
问题描述
我有一个名为Object的类存储一些数据。
我想使用这样的函数通过引用返回:
对象& return_Object();然后,在我的代码中,我会这样调用:
Object myObject = return_Object();
我写了这样的代码,它编译。但是,当我运行代码,我一直得到seg故障。通过引用返回类对象的正确方法是什么?
解决方案你可能返回一个堆栈上的对象。也就是说, return_Object()
可能如下所示:
return_Object()
{
对象object_to_return;
// ... do stuff ...
return object_to_return;
}
如果这是你在做什么, object_to_return
已经超出作用域,并在 return_Object
结束时被销毁,因此 myObject
是指不存在的对象。您需要返回值,或者返回在更广泛的范围中声明的 Object
或者在堆上返回 new
ed。
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?
解决方案 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;
}
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 ++中通过引用返回类对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!