【问题标题】:Adding member boost::ptr_vector<>添加成员 boost::ptr_vector<>
【发布时间】:2011-11-09 15:28:42
【问题描述】:

我有休闲课:

class CpuUsage {
public:
    CpuUsage();
    virtual ~CpuUsage();

    void SetCpuTotalTime(CpuCore _newVal);
    CpuCore GetCpuTotalTimes();

    void AddSingleCoreTime(CpuCore& newval);
private:
    CpuCore total;
    boost::ptr_vector<CpuCore> cpuCores;
};

class CpuCore {

public:
    CpuCore();
    CpuCore(int _coreId, long _user, long _nice, long _sysmode,
        long _idle, long _iowait, long _irq, long _softirq, long _steal,
        long _guest);

//all variable declarations...
}

为了将 CpuCore 对象添加到 cpuCores 向量中,我应该添加一个指针吗?或者我可以复制值,通常情况下,例如:

void CpuUsage::AddSingleCoreTime(CpuCore _newVal) {
    cpuCores.push_back(_newVal);
}

使用 CpuCore *_newVal 参数,我有以下错误:
../src/usage/CpuUsage.h:42:错误:'boost::ptr_vector > CpuUsage::cpuCores' 是私有的 ../src/NodeInfoGather.cpp:73:错误:在此上下文中

这里的向量是私有的有什么问题?

谢谢,

【问题讨论】:

  • 你应该添加一个指针,boost::ptr_vector&lt;&gt; 拥有它的指针和它们指向的东西。为什么不只使用std::vector&lt;&gt;
  • 我在这篇文章中使用了 boost ptr 矢量:stackoverflow.com/questions/2693651/…
  • 在您给定的代码中,您似乎没有超过 CpuCore 的多态性。但是贴出来的代码不是真的,AddSingleCoreTime的声明和定义不一样。
  • 你应该或不应该写什么取决于你还没有告诉我们的事情。在您的设计中,所涉及的对象之间期望的所有权关系是什么?您是否熟悉 C++ 中资源管理的“所有权”概念?你认为 boost::ptr_vector 的目的是什么?
  • @sellibitze - 这就是我现在正在苦苦挣扎的事情。我不知道资源管理中的这种所有权概念,对不起。我希望向量能够以某种方式保存我的元素,当我销毁类时,它们也会被销毁并且它们的内存是空闲的。

标签: c++ boost ptr-vector


【解决方案1】:

您必须添加指向ptr_vector 的指针。请注意,它将获得该指针的所有权,因此只需这样做

cpuCores.push_back(&_newVal);

可能会把事情搞砸。如果你真的想要它(你的问题并不清楚)你可以实现一个virtual constructor

【讨论】:

  • 是的,它确实有效。但是我会修改我的架构,也许我真的不需要指针向量 - 我仍然需要了解 c++ 的这种所有权
猜你喜欢
  • 1970-01-01
  • 2011-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多