Reputation: 2595
I have a base class
with a priority_queue
like this:
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
:
void Obj::set ()
{
BaseServer& myObj = BaseFactory::getBase();
myObj.set(this); //<------ won't compile :(
}
And this set()
will call a set()
on my base class
:
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
....
But it won't even compile, and I'm a bit lost...
Any ideas what I'm missing here?
Upvotes: 0
Views: 489
Reputation: 55887
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. Idea of your code is strange, but, it's actually better to use shared_ptr
and 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
. And of course you should use shared_ptr<Obj>
in code, that calls 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();
Upvotes: 5
Reputation: 3409
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);
Upvotes: 0