C ++最佳实践:返回引用与对象 [英] C++ best practice: Returning reference vs. object

查看:84
本文介绍了C ++最佳实践:返回引用与对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习C ++,并试图了解返回的对象。我似乎看到了两种方法,并且需要了解什么是最佳实践。

I'm trying to learn C++, and trying to understand returning objects. I seem to see 2 ways of doing this, and need to understand what is the best practice.

选项1:

QList<Weight *> ret;
Weight *weight = new Weight(cname, "Weight");
ret.append(weight);
ret.append(c);
return &ret;

选项2:

QList<Weight *> *ret = new QList();
Weight *weight = new Weight(cname, "Weight");
ret->append(weight);
ret->append(c);
return ret;

(当然,我也许也不了解)。

(of course, I may not understand this yet either).

哪种方法被认为是最佳实践,应该遵循?

Which way is considered best-practice, and should be followed?

推荐答案

选项1 是有缺陷的。声明对象时

Option 1 is defective. When you declare an object

QList<Weight *> ret;

它仅存在于本地范围内。函数退出时销毁它。但是,您可以使用

it only lives in the local scope. It is destroyed when the function exits. However, you can make this work with

return ret; // no "&"

现在,尽管 ret 被销毁了,

Now, although ret is destroyed, a copy is made first and passed back to the caller.

这是通常首选的方法。实际上,复制和销毁操作(实际上什么也没做)通常被消除或优化后,您将获得一个快速,优雅的程序。

This is the generally preferred methodology. In fact, the copy-and-destroy operation (which accomplishes nothing, really) is usually elided, or optimized out and you get a fast, elegant program.

选项2 有效,但是您有了指向堆的指针。查看C ++的一种方法是该语言的目的是避免诸如此类的手动内存管理。有时您确实想管理堆上的对象,但是选项1仍然允许:

Option 2 works, but then you have a pointer to the heap. One way of looking at C++ is that the purpose of the language is to avoid manual memory management such as that. Sometimes you do want to manage objects on the heap, but option 1 still allows that:

QList<Weight *> *myList = new QList<Weight *>( getWeights() );

其中 getWeights 是您的示例函数。 (在这种情况下,您可能必须定义一个副本构造函数 QList :: QList(QList const&),但是像前面的示例一样,它可能不会被调用。 )

where getWeights is your example function. (In this case, you may have to define a copy constructor QList::QList( QList const & ), but like the previous example, it will probably not get called.)

同样,您可能应该避免使用指针列表。该列表应直接存储对象。尝试使用 std :: list …练习语言功能比练习实现数据结构更重要。

Likewise, you probably should avoid having a list of pointers. The list should store the objects directly. Try using std::list… practice with the language features is more important than practice implementing data structures.

这篇关于C ++最佳实践:返回引用与对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆