返回指向接口的指针,但将所有权和生命周期保留给提供者

Returning pointers to interfaces but keep ownership & lifetime to the provider

我有以下一组库

我的问题是关于 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;
}

这些是我想要保留的语义。

但是如果需要 returned 一组对象,之前的界面就没有用了。

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 到 return 指向其具体对象由提供者拥有的接口的指针,同时保持以下语义(这是自然的return引用对象 (&) 的语义)?

如果你想return引用,你可以使用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());
}