如果对象不存在,函数以值或特殊值返回类对象的最佳签名是什么?
对于返回多个对象的函数,函数原型是
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.
更多推荐
发布评论