[英]How to return a class object by reference in C++?
我有一个名为 Object 的类,它存储一些数据。
我想使用这样的函数通过引用返回它:
Object& return_Object();
然后,在我的代码中,我会这样称呼它:
Object myObject = return_Object();
我已经编写了这样的代码并且它可以编译。 但是,当我运行代码时,我始终遇到段错误。 通过引用返回类对象的正确方法是什么?
您可能正在返回堆栈上的对象。 也就是说, return_Object()
可能看起来像这样:
Object& return_Object()
{
Object object_to_return;
// ... do stuff ...
return object_to_return;
}
如果这是您正在做的事情,那么您return_Object
走运了 - object_to_return
已超出范围并在return_Object
结束时被破坏,因此myObject
指的是一个不存在的对象。 您要么需要按值返回,要么返回在更大范围内声明的Object
或将new
ed 返回到堆上。
你只能使用
Object& return_Object();
如果返回的对象具有比函数更大的范围。 例如,如果您有一个封装了它的类,则可以使用它。 如果在函数中创建对象,请使用指针。 如果要修改现有对象,请将其作为参数传递。
class MyClass{
private:
Object myObj;
public:
Object& return_Object() {
return myObj;
}
Object* return_created_Object() {
return new Object();
}
bool modify_Object( Object& obj) {
// obj = myObj; return true; both possible
return obj.modifySomething() == true;
}
};
您只能通过引用返回非本地对象。 析构函数可能使某些内部指针无效,或者其他什么。
不要害怕返回值—— 它很快!
我将向您展示一些示例:
const string &dontDoThis(const string &s)
{
string local = s;
return local;
}
您不能通过引用返回local
,因为local
在dontDoThis
主体的末尾被销毁。
const string &shorterString(const string &s1, const string &s2)
{
return (s1.size() < s2.size()) ? s1 : s2;
}
在这里,您可以通过引用返回s1
和s2
因为它们是在shorterString
之前定义的。
char &get_val(string &str, string::size_type ix)
{
return str[ix];
}
使用代码如下:
string s("123456");
cout << s << endl;
char &ch = get_val(s, 0);
ch = 'A';
cout << s << endl; // A23456
get_val
可以通过引用返回s
的元素,因为调用后s
仍然存在。
class Student
{
public:
string m_name;
int age;
string &getName();
};
string &Student::getName()
{
// you can return by reference
return m_name;
}
string& Test(Student &student)
{
// we can return `m_name` by reference here because `student` still exists after the call
return stu.m_name;
}
用法示例:
Student student;
student.m_name = 'jack';
string name = student.getName();
// or
string name2 = Test(student);
class String
{
private:
char *str_;
public:
String &operator=(const String &str);
};
String &String::operator=(const String &str)
{
if (this == &str)
{
return *this;
}
delete [] str_;
int length = strlen(str.str_);
str_ = new char[length + 1];
strcpy(str_, str.str_);
return *this;
}
然后你可以像这样使用上面的operator=
:
String a;
String b;
String c = b = a;
好吧,它在代码中可能不是一个非常漂亮的解决方案,但它在您的函数界面中确实非常漂亮。 而且它也非常有效。 如果第二个对您更重要(例如,您正在开发一个库),这是理想的。
诀窍是这样的:
A a = b.make();
在内部转换为 A 的构造函数,即就像你写了A a(b.make());
.b.make()
应该产生一个带有回调函数的新类。 这是我的最小示例。 只检查main()
,你可以看到它很简单。 内功不是。
从速度上看:一个Factory::Mediator
类的大小只有2个指针,比1多但不多。 这是整个事物中唯一以价值转移的对象。
#include <stdio.h>
class Factory {
public:
class Mediator;
class Result {
public:
Result() {
printf ("Factory::Result::Result()\n");
};
Result(Mediator fm) {
printf ("Factory::Result::Result(Mediator)\n");
fm.call(this);
};
};
typedef void (*MakeMethod)(Factory* factory, Result* result);
class Mediator {
private:
Factory* factory;
MakeMethod makeMethod;
public:
Mediator(Factory* factory, MakeMethod makeMethod) {
printf ("Factory::Mediator::Mediator(Factory*, MakeMethod)\n");
this->factory = factory;
this->makeMethod = makeMethod;
};
void call(Result* result) {
printf ("Factory::Mediator::call(Result*)\n");
(*makeMethod)(factory, result);
};
};
};
class A;
class B : private Factory {
private:
int v;
public:
B(int v) {
printf ("B::B()\n");
this->v = v;
};
int getV() const {
printf ("B::getV()\n");
return v;
};
static void makeCb(Factory* f, Factory::Result* a);
Factory::Mediator make() {
printf ("Factory::Mediator B::make()\n");
return Factory::Mediator(static_cast<Factory*>(this), &B::makeCb);
};
};
class A : private Factory::Result {
friend class B;
private:
int v;
public:
A() {
printf ("A::A()\n");
v = 0;
};
A(Factory::Mediator fm) : Factory::Result(fm) {
printf ("A::A(Factory::Mediator)\n");
};
int getV() const {
printf ("A::getV()\n");
return v;
};
void setV(int v) {
printf ("A::setV(%i)\n", v);
this->v = v;
};
};
void B::makeCb(Factory* f, Factory::Result* r) {
printf ("B::makeCb(Factory*, Factory::Result*)\n");
B* b = static_cast<B*>(f);
A* a = static_cast<A*>(r);
a->setV(b->getV()+1);
};
int main(int argc, char **argv) {
B b(42);
A a = b.make();
printf ("a.v = %i\n", a.getV());
return 0;
}
返回已启动的对象并不是一个很好的做法,因为它确实超出了范围。 在极少数情况下,这是理想的选择。 如果类是引用计数智能指针或其他一些智能指针,它实际上可以完成。 引用计数智能指针的引用计数是如何工作的?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.