gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 04:59:10 25 4
gpt4 key购买 nike

我有以下一组库

  • 一些接口(interface)
  • 提供程序库。它将为对象提供已定义的接口(interface)。
  • 消费者图书馆。它使用已定义接口(interface)的对象。
  • 协调员图书馆。使用提供者创建对象并将它们传递给消费者。

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

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

  • 提供者拥有该对象,并且
  • 对象的生命周期与提供者相同。

但是如果需要返回一组对象,以前的接口(interface)就没有用了。

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

  • 提供者拥有对象并且
  • 对象的生命周期与提供者相同。

最佳答案

如果要返回引用,可以使用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());
}

关于c++ - 返回指向接口(interface)的指针,但将所有权和生命周期保留给提供者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51352242/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com