-2
class MyClass {
    public:
       register_callback(int, void*);
}

typedef boost::shared_ptr<MyClass> myClass_p;

class MyOtherClass {
  public: 
    registerItem(std::pair<std::string, myClass_p>insertItem) {
      auto foo = insertItem.second;
      void *bar = static_cast<void*>(foo);
 }

Given the above code why am I getting "static_cast: cannot convert from myClass_p to void *. I thought you could cast any pointer to a void *.

1 Answers1

3

foo isn't a pointer. It's an object. That object happens to be a boost::shared_ptr<MyClass> and so semantically a smart pointer. But it isn't a pointer.

Assuming the dubious hypothesis that what you're doing makes sense you need:

void *bar = foo.get();

boost::shared_ptr<MyClass>::get() returns a pointer to the shared object (or nullptr if empty).

Persixty
  • 8,165
  • 2
  • 13
  • 35
  • 1
    Thanks, I thought smart pointers could be used anywhere regular pointers could be used. Now of I'm having trouble going the other way `myClass_p pointer(static_cast(bar));` gives me cannot convert from void* to MyClass* – Claudius Turner Jul 25 '17 at 14:09
  • @ClaudiusTurner In C++ any pointer can be cast to `void *` (I removed the redundant `static_cast<>` but `void *` can't be cast back as easily. Rightly so. The type-system can't assure you the cast back is valid (it can't trace what it was cast from) so you do need `static_cast<>` on the way back. That's why I called what you're doing 'dubious'. It's rarely the case in modern C++ to go via `void *` unless maybe interfacing with legacy because of these type-system risks. C lets you case freely from `void *` but I consider that a blunder fixed in C++. – Persixty Jul 25 '17 at 14:14