无法投射为无效 *

can't cast to void *

本文关键字:无效      更新时间:2023-10-16
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);
}

鉴于上面的代码,为什么我得到"static_cast:无法从 myClass_p 转换为 void *。 我以为你可以将任何指针投射到一个空隙*。

foo

不是指针。它是一个对象。该对象恰好是一个boost::shared_ptr<MyClass>,因此在语义上是一个智能指针。但这不是一个指针。

假设你正在做的事情是有意义的可疑假设,你需要:

void *bar = foo.get();

boost::shared_ptr<MyClass>::get()返回指向共享对象的指针(如果为空,则返回nullptr(。