[英]C++11 - How to push this object into priority_queue with vector of shared_ptr?
I have a base class
with a priority_queue
like this: 我有一个具有
priority_queue
的base class
,如下所示:
class base
{
//...
std::priority_queue<std::shared_ptr<Obj>, std::vector<std::shared_ptr<Obj>>, obj_less> obj_queue;
//...
}
On my Obj class
, I have a method that should push this object into the priority_queue
: 在我的
Obj class
,我有一个方法应将该对象推送到priority_queue
:
void Obj::set ()
{
BaseServer& myObj = BaseFactory::getBase();
myObj.set(this); //<------ won't compile :(
}
And this set()
will call a set()
on my base class
: 这个
set()
将在我的base class
上调用set()
:
void base::set(const Obj& o)
{
obj_queue.push(o);
}
I want to use the this
, to get the pointer to this same Obj
, and push it into my vector
, inside my priority_queue
.... 我想使用
this
,获取指向同一Obj
的指针,并将其推入我的vector
,位于我的priority_queue
...内。
But it won't even compile, and I'm a bit lost... 但是它甚至不会编译,我有点迷路了。。。
Any ideas what I'm missing here? 有什么想法我在这里想念的吗?
You actually shouln't do this, since, it's really bad idea and you will have no problems only and only if you has raw pointer on Obj
in place of calling set
function. 实际上,您不应该这样做,因为,这确实是个坏主意,只有在
Obj
上有原始指针代替调用set
函数的情况下,您才不会有任何问题。 Idea of your code is strange, but, it's actually better to use shared_ptr
and enable_shared_from_this
. 代码的想法很奇怪,但是实际上最好使用
shared_ptr
和enable_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 :(
}
};
And BaseServer
should have function set
, that receives shared_ptr
on Obj
. 而且
BaseServer
应该具有函数set
,该函数在Obj
上接收shared_ptr
。 And of course you should use shared_ptr<Obj>
in code, that calls set
. 当然,您应该在代码中使用
shared_ptr<Obj>
,它调用set
。 For example something like this 例如这样的事情
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();
myObj.set(this);
passes a pointer, but 传递指针,但是
void base::set(const Obj& o)
expects an object. 需要一个对象。
Do 做
void base::set(const Obj *o)
{
obj_queue.push(*o);
}
Or 要么
myObj.set(*this);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.