0

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();
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
pavikirthi
  • 1,569
  • 3
  • 17
  • 26
  • Careful with the tagging. You won't be working in all of those version tags at the same time and this definitely isn't C. I removed C and all of the Standard revisions except the most recent. If you'd prefer C++11 or 14, feel free to replace 17. – user4581301 May 19 '20 at 18:56
  • 1
    As for converting a `shared_ptr` to `void*`, don't. It's not possible without defeating the point of using a shared pointer in the first place. `void` pointers are too simple. They don't even know what they point at, let alone that what they point at has special destruction rules. – user4581301 May 19 '20 at 18:59
  • See also ["Why shared_from_this can't be used in constructor from technical standpoint?"](https://stackoverflow.com/questions/31924396/why-shared-from-this-cant-be-used-in-constructor-from-technical-standpoint). – G.M. May 19 '20 at 19:08

1 Answers1

2

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 to void *

You can use the member function get. The resulting pointer implicitly converts to void*.

eerorika
  • 232,697
  • 12
  • 197
  • 326