函数按值返回对象,如果对象不存在则返回任何内容(Function returning an object by value or nothing if object doesn't exis

编程入门 行业动态 更新时间:2024-10-08 04:28:03
函数按值返回对象,如果对象不存在则返回任何内容(Function returning an object by value or nothing if object doesn't exists)

如果对象不存在,函数以值或特殊值返回类对象的最佳签名是什么?

对于返回多个对象的函数,函数原型是

QList<X> getSomeXOrNothing(); 如果有对象,它返回对象列表;如果没有对象,则返回空列表,这完全符合我的需要并且便于使用。

现在,我知道函数只能返回单个对象或什么都没有,最好的签名是什么? 返回原始指针是不可取的,因为它有可能发生错误泄漏。

我在返回共享指针或仍返回具有单个值的列表之间进行辩论:

QList<X> getSingleXOrNothing(); QSharedPointer<X> getSingleXOrNothing();

但我想知道是否有更好的方法来做到这一点 - 共享指针增加了不必要的开销,而返回列表是有争议的,因为我知道列表只能包含一个对象。

编辑:所有QList,SharedPointr和QVariant都是可以接受的选项,但我正在为每个字节都很重要的嵌入式设备开发,并且会有很多调用这个函数 - 所以试图找到最佳容器给定的条件 - 它是一个对象或没有。

What would be the best signature of a function returning a class object by value or something special if object does not exists?

For function returning more than one object, function prototype is

QList<X> getSomeXOrNothing(); it returns list of objects if there are objects, or empty list if there is no objects, which fully suits my needs and is convenient to work with.

Now, I know that function can only return single object or nothing, what would be the best signature? Returning a raw pointer is not desirable since it has potential for error leaks.

I'm debating between returning shared pointer or still returning a list with a single value:

QList<X> getSingleXOrNothing(); QSharedPointer<X> getSingleXOrNothing();

but I am wondering if there are any better ways to do that - shared pointer adds unnecessary overhead, while returning a list is controversial since I know list can contain only one object.

EDIT: All of QList, SharedPointr and QVariant are acceptable options, but I'm developing for embedded device where every byte counts, and there will be a lot of calls to this function - so trying to find optimal container given conditions - it is one object or nothing.

最满意答案

您可以使用“选项模式”。 基本思路是:

template <typename T> class Optional { private: bool valueIsPresent; T value; }

然后,从该函数中可以返回Optional<YourType> 。 然后,客户端代码可以在尝试访问并使用它之前检查某个值是否有效存在。

You can use the "Option Pattern". The basic idea is:

template <typename T> class Optional { private: bool valueIsPresent; T value; }

Then, from the function you can return Optional<YourType>. Client code can then check if a value is effectively present before trying to access it and use it.

更多推荐

本文发布于:2023-08-04 19:50:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1422173.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   不存在   函数   内容   object

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!