这个shared_ptr是如何自动转换为原始指针的
How is this shared_ptr automatically converted to a raw pointer?
我现在正在学习C++11的enable_shared_from_this
;有一个例子让我很困惑:shared_from_this()
返回的shared_ptr
类型如何转换为这个原始指针?
#include <iostream>
#include <memory>
#include <functional>
struct Bar {
Bar(int a) : a(a) {}
int a;
};
struct Foo : public std::enable_shared_from_this<Foo> {
Foo() { std::cout << "Foo::Foon"; }
~Foo() { std::cout << "Foo::~Foon"; }
std::shared_ptr<Bar> getBar(int a)
{
std::shared_ptr<Bar> pb(
new Bar{a}, std::bind(&Foo::showInfo, shared_from_this(), std::placeholders::_1)
);
return pb;
}
void showInfo(Bar *pb)
{
std::cout << "Foo::showInfo()n";
delete pb;
}
};
int main()
{
std::shared_ptr<Foo> pf(new Foo);
std::shared_ptr<Bar> pb = pf->getBar(10);
std::cout << "pf use_count: " << pf.use_count() << std::endl;
}
这是std::bind
的智能,而不是指针。
如Callable中所述,当调用指向非静态成员函数的指针或指向非静态数据成员的指针时,第一个参数必须是指向将访问其成员的对象的引用或指针(可能包括智能指针,如std::shared_ptr和std::unique_ptr)。
bind
的实现使其可以接受智能指针而不是原始指针。
您可以在glibc++实现中看到bind
内部调用invoke
:
// Call unqualified
template<typename _Result, typename... _Args, std::size_t... _Indexes>
_Result
__call(tuple<_Args...>&& __args, _Index_tuple<_Indexes...>)
{
return std::__invoke(_M_f,
_Mu<_Bound_args>()(std::get<_Indexes>(_M_bound_args), __args)...
);
}
std::invoke
可以开箱即用地处理智能事物(指针、引用包装器等):
INVOKE(f, t1, t2, ..., tN)
定义如下:如果
f
是指向类T
:的成员函数的指针
- 如果
std::is_base_of<T, std::decay_t<decltype(t1)>>::value
为真,则INVOKE(f, t1, t2, ..., tN)
等价于(t1.*f)(t2, ..., tN)
- 如果
std::decay_t<decltype(t1)>
是std::reference_wrapper
的特化,则INVOKE(f, t1, t2, ..., tN)
等价于(t1.get().*f)(t2, ..., tN)
- 如果
t1
不满足前面的项,则INVOKE(f, t1, t2, ..., tN)
等效于((*t1).*f)(t2, ..., tN)
相关文章:
- 是否可以将llvm::FunctionType转换为C/C++原始函数指针
- 如何将唯一指针的 std::vector 转换为原始指针的 std::span?
- 如何在连接器 C++ 中将原始字节转换为字符串
- 将以 null 结尾的字节字符串转换为原始字符串文本
- Qt - 将空指针(原始数据)转换为 QImage 并将其显示在标签上
- 将 std::vector<int> 从原始内存转换为数组
- 原始指针在放置并推送到智能指针向量时是否会自动转换为智能指针?
- 在对原始字符串进行一些处理后返回(或转换)原始字符串
- 将多个非原始递归调用转换为迭代解决方案
- 将原始视频图像转换为VPX编码器的I420
- CAN模板类型推理考虑原始操作类型转换
- 为什么双转换到看似任何原始的常量参考
- C++ Arduino:向下转换后,子字段不引用原始地址
- 使用可变参数将函数转换回原始签名
- 将 std::conditional 与不可转换类型(原始与指针)一起使用
- 这个shared_ptr是如何自动转换为原始指针的
- 将原始像素数据转换为qpixmap
- 带有布尔转换的变量的原始打印:意外行为
- C++字符串管理通过字典匹配转换原始字符串
- Qt/C++-转换原始二进制数据并将其显示为图像(即QImage)