我有以下库
我的问题是关于提供者的API设计。让我们举个例子:
class Provider
{
// One way is to return a reference to an owned object.
// This is useful because no pointers are returned
// so that no one will be asking about ownership and lifetime.
// - The provider owns the object and
// - The lifetime of the object is the same as the provider.
const ObjectInterface &getObject(int id) const;
}
这些是我要保留的语义。
但是如果需要返回一组对象,则先前的界面将无济于事。
class Provider
{
// This is the easiest way.
// Is this the best way?
std::vector< ObjectInterface * > allObjects() const;
// Using shared_ptr violates the semantics described above
// and requires allocation on heap.
// Using weak_ptr violates the semantics described above
// and requires allocation on heap.
// Using unique_ptr violates the semantics described above
// and requires allocation on heap.
}
是否有更好的方法来设计此API,以返回指向其具体对象由提供者拥有的接口的指针,同时保留以下语义(这是将引用(&)返回给对象的自然语义) ?
答案 0 :(得分:1)
如果要返回引用,可以使用std::reference_wrapper
:
#include <functional>
#include <vector>
#include <cstdio>
struct A
{
std::vector<int> objs{1, 2, 3};
std::vector<std::reference_wrapper<int>> allObjects()
{
return std::vector<std::reference_wrapper<int>>(objs.begin(), objs.end());
}
};
int main()
{
A a;
for (auto ref : a.allObjects())
printf("%i\n", ref.get());
}