将void*转换为某种类型的shared_ptr
Convert void * to shared_ptr of a type
在下面的代码中,我试图将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" );
如何将void指针转换为类型的共享指针?
假设您不能更改PrintA
的声明,那么您的PrintA
定义应该如下所示:
void PrintA(void *aptr)
{
A* a1 = reinterpret_cast<A*>(aptr);
a1->Show();
}
当你把一个指针传给它的时候。由于您不收回所有权,因此无需创建std::shared_ptr
。如果您需要共享所有权,则必须修改A
以允许使用share_from_this
。
相关文章:
- ArduinoJson 6.15.2:JsonObject没有命名类型
- 防止主数据类型C++的隐式转换
- 大量序列中核苷酸类型的快速计数
- 如何从C++中的依赖类型中获得它所依赖的类型
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 是否可以初始化不可复制类型的成员变量(或基类)
- 如何获取std::result_of函数的返回类型
- 从父命名空间重载类型
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- Openssl 1.1.1d无效使用不完整的类型"struct dsa_st"
- 访问者访问变体并返回不同类型时出错
- 在VS2010-VS2015下编译时,如何使用decltype作为较大类型表达式的LHS
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 模板元程序查找相似的连续类型名称
- 是否可以从int转换为enum类类型
- 构造函数正在调用一个使用当前类类型的函数
- 我应该使用什么来代替void作为变体中的替代类型之一
- 在shared_from_this()中的错误类型(在继承类中)(是否有dyn.type-ware shared Poi