【问题标题】:C++11 - How to push this object into priority_queue with vector of shared_ptr?C++11 - 如何使用 shared_ptr 向量将此对象推入priority_queue?
【发布时间】:2015-10-06 21:39:29
【问题描述】:

我有一个base class 和一个priority_queue,如下所示:

class base
{
   //...
   std::priority_queue<std::shared_ptr<Obj>, std::vector<std::shared_ptr<Obj>>, obj_less> obj_queue;
   //...
}

在我的Obj class 上,我有一个方法可以将此对象推入priority_queue

void Obj::set ()
{
    BaseServer& myObj = BaseFactory::getBase();
    myObj.set(this); //<------ won't compile :(
}

这个set() 将在我的base class 上调用set()

void base::set(const Obj& o)
{
    obj_queue.push(o);
}

我想使用this 来获取指向同一个Obj 的指针,并将其推入我的vector 中,在我的priority_queue 中......

但它甚至不会编译,我有点迷茫......

任何想法我在这里缺少什么?

【问题讨论】:

  • 您可能需要myObj.set(*this);void base::set(const Obj *o)
  • 将您的错误添加到问题中

标签: c++ c++11 vector shared-ptr priority-queue


【解决方案1】:

您实际上不应该这样做,因为这是一个非常糟糕的主意,只有当您在 Obj 上使用原始指针而不是调用 set 函数时,您才会遇到问题。您的代码的想法很奇怪,但实际上最好使用shared_ptrenable_shared_from_this

class Obj : public std::enable_shared_from_this<Obj>
{
public:
   // ...
   void set()
   {
      BaseServer& myObj = BaseFactory::getBase();
      myObj.set(std::shared_from_this()); //<------ won't compile :(
   }
};

BaseServer 应该有函数set,在Obj 上接收shared_ptr。当然你应该在代码中使用shared_ptr&lt;Obj&gt;,它调用set。比如这样的

class Obj : public std::enable_shared_from_this<Obj>
{
private:
   Obj() {}
public:
   static std::shared_ptr<Obj> create()
   {
      return std::make_shared<Obj>();
   }
   // rest code
};

// code, that calls set function
auto object = Obj::create();
object->set();

【讨论】:

    【解决方案2】:
    myObj.set(this);
    

    传递一个指针,但是

    void base::set(const Obj& o)
    

    需要一个对象。

    void base::set(const Obj *o)
    {
        obj_queue.push(*o);
    }
    

    或者

     myObj.set(*this);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-06
      • 2017-01-18
      • 2014-04-15
      • 2016-07-15
      • 1970-01-01
      • 2013-02-16
      • 1970-01-01
      相关资源
      最近更新 更多