C++ 11 - 如何使用shared_ptr向量将此对象推入priority_queue?

waa*_*919 0 c++ vector priority-queue shared-ptr c++11

我有base class一个priority_queue这样的:

class base
{
   //...
   std::priority_queue<std::shared_ptr<Obj>, std::vector<std::shared_ptr<Obj>>, obj_less> obj_queue;
   //...
}
Run Code Online (Sandbox Code Playgroud)

在我Obj class,我有一个方法,应该将此对象推入priority_queue:

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

set()会打电话给set()base class:

void base::set(const Obj& o)
{
    obj_queue.push(o);
}
Run Code Online (Sandbox Code Playgroud)

我想使用this,获取指向同样的指针Obj,然后将它推入我的vector内部priority_queue....

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

我在这里缺少什么想法?

For*_*veR 5

你实际上不应该这样做,因为,这是一个非常糟糕的主意,只有你有原始指针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 :(
   }
};
Run Code Online (Sandbox Code Playgroud)

并且BaseServer应该有set接收的shared_ptr功能Obj.当然,您应该shared_ptr<Obj>在代码中使用,即调用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();
Run Code Online (Sandbox Code Playgroud)