Reputation: 1655
In a C++ class, I am trying to use shared_ptr
, but instead of using this
I am trying to use shared_from_this()
. In the constructor, I am trying to create an object of a struct which expects a void*
. I am not sure how I can convert a shared_ptr
to a void*
which can be passed as the parameters to the struct which is expecting void*
.
Callback.cpp
struct CObj{
int val;
void* context;
};
class A : std::enable_shared_from_this<A>{
private:
Cobj mCobj;
public:
A(){
mCobj = (CObj){5, shared_from_this()};
}
~A(){
}
Cobj getObjref(){
return mCObj;
}
};
std::shared_ptr p = std::shared_ptr<A>(new A);
Cobj invokeCfunc = p->getObjref();
Upvotes: 0
Views: 253
Reputation: 238311
You cannot call shared_from_this
in a contructor. You also don't need to because what you wanted was void*
. this
implicitly converts to void*
. You don't need access to the shared pointer in the first place.
This is very simple:
A(): mCobj{5, this} {
Note that if you make a copy of A
, then the copy will point to the object it was copied from. Consider whether this is what you want, and if not, then change the copy and move constructor and assignment operator to behave as you would want them to behave.
I am not sure how can I convert a
shared_ptr
tovoid *
You can use the member function get
. The resulting pointer implicitly converts to void*
.
Upvotes: 2