创建包含原子值作为其成员的类型的成员变量

create member variable of type that contains atomic value as its member

我正在使用第三方库,其 class 包含 atomic<double>。现在库 returns 在调用函数时引用了那个 class 对象。现在我想将该引用保存在某个地方以便在我的应用程序工作流程中重用它。

Here is the actual class from the third party lib
Here is the function that returns the reference

因为它拥有原子值,所以我无法复制 class 对象(上面 link 中的 Gauge),而且我也无法更改第三方库此时此刻。有什么解决方法吗?

我尝试将返回的参考值存储在 unique_ptr<Gauge>

std::unique_ptr<prometheus::Gauge> cpuUsageInPercent = std::make_unique<prometheus::Gauge>(
            prometheus::BuildGauge()
                    .Name("cpu_usage_percent")
                    .Help("cpu usage in percent")
                    .Register(*m_registry)
                    .Add({}));

但我收到以下错误

/usr/include/c++/11/bits/unique_ptr.h:962:30: error: use of deleted function ‘prometheus::Gauge::Gauge(const prometheus::Gauge&)’
  962 |     { return unique_ptr<_Tp>(new _Tp(std::forward<_Args>(__args)...)); }

TL;DR

写这个怎么样?

Gauge & g = prometheus::BuildGauge()
                    .Name("cpu_usage_percent")
                    .Help("cpu usage in percent")
                    .Register(*m_registry)
                    .Add({});

长答案

如果你有一个返回引用的函数,比如

X &f();

然后你可以简单地获取结果的地址并存储它,就像这样:

X * ptr = &f();

然后您可以通过指针引用该对象。您可以四处复制指针,从而将其保存在应用程序中任何您想要的位置。您也可以像这样通过引用来引用对象:

X & obj = f();

如果您将某物放入 std::unique_ptr<X>,则表示您成为该对象的唯一 所有者。但是,据我所知,您只想参考。因此,一个简单的原始指针可能正是您所需要的。

如果您使用 std::make_unique<X>() 创建一个对象,那么您必须将参数传递给该函数,这些参数被接受为 X 的构造函数的参数。 Gauge class 不提供以 Gauge & 作为参数的构造函数。