Search code examples
c++structshared-ptr

initialize struct with shared_ptr<void>


I keep running into an error that no matching constructor for initialization of 'std::shared_ptr<void>' which makes sense, but I don't know where to begin.

Here is what I'm working with.

#include <memory>                                                                                                                                                             

struct Container {                                                             
  int type;                                                                    
  std::shared_ptr<void> payload;                                               

  Container(int t, const void *p) : type(t), payload(p) { }                    
};                                                                             

int main() {                                                                   
  return 0;                                                                    
}

I'm trying to make a generic container using a shared_ptr with type of void. I was going to do a switch on the type and then just cast the payload into the appropriate type.

I figured I could just do something like Container ctn(1, new Data()); but I think I might have that wrong as well.

Thanks.


Solution

  • You're trying to initialise a pointer to void with a pointer to const void, which is indeed illegal. The "smartness" of the pointer does not matter, this would fail for ordinary pointers as well.

    You either need to change the type of payload to std::shared_ptr<const void>, or (probably more what you actually want) change the type of p to void*.


    Note, however, that while this will technically solve the immediate problem, it can introduce a more fundamental one. Under this design, payload will know nothing about the actual type to which it points, so it will not call a destructor of Data when the last reference goes out. You should probably rethink the entire design to use suitably typed pointers.