c++ 将void * 转换为类型的shared_ptr

inn6fuwd  于 2023-06-07  发布在  其他
关注(0)|答案(1)|浏览(268)

在下面的代码中,我试图将void* 转换为类型的shared_ptr:

#include <iostream>
#include <memory>
class A
{
public:
    A() { l = 0; }
    int l;
    void Show() { std::cout << l << "\n"; }
};

void PrintA(void *aptr)
{
    std::shared_ptr<A> a1;
    a1.reset(aptr);
    a1->Show();
}

int main()
{
    std::shared_ptr<A> a(new A());
    PrintA(a.get());
}

但我得到下面的编译错误:

$ c++ -std=c++14 try20.cpp
In file included from C:/tools/mingw64/x86_64-w64-mingw32/include/c++/bits/shared_ptr.h:52:0,
                 from C:/tools/mingw64/x86_64-w64-mingw32/include/c++/memory:82,
                 from try20.cpp:2:
C:/tools/mingw64/x86_64-w64-mingw32/include/c++/bits/shared_ptr_base.h: In instantiation of 'std::__shared_ptr<_Tp, _Lp>::__shared_ptr(_Tp1*) [with _Tp1 = void; _Tp = A; __gnu_cxx::_Lock_policy _Lp = (__gnu_cxx::_Lock_policy)2u]':
C:/tools/mingw64/x86_64-w64-mingw32/include/c++/bits/shared_ptr_base.h:1023:4:   required from 'void std::__shared_ptr<_Tp, _Lp>::reset(_Tp1*) [with _Tp1 = void; _Tp = A; __gnu_cxx::_Lock_policy _Lp = (__gnu_cxx::_Lock_policy)2u]'
try20.cpp:14:14:   required from here
C:/tools/mingw64/x86_64-w64-mingw32/include/c++/bits/shared_ptr_base.h:871:39: error: invalid conversion from 'void*' to 'A*' [-fpermissive]
         : _M_ptr(__p), _M_refcount(__p)
                                       ^
C:/tools/mingw64/x86_64-w64-mingw32/include/c++/bits/shared_ptr_base.h:874:4: error: static assertion failed: incomplete type
    static_assert( !is_void<_Tp1>::value, "incomplete type" );

如何将一个空指针转换为一个类型的共享指针?

ou6hu8tu

ou6hu8tu1#

假设你不能改变PrintA的声明,你的PrintA定义应该是这样的:

void PrintA(void *aptr)
{
    A* a1 = reinterpret_cast<A*>(aptr);
    a1->Show();
}

当你向它传递一个指针时。因为你没有收回所有权,所以不需要创建std::shared_ptr。如果您需要共享所有权,则必须修改A以允许使用share_from_this

相关问题