这个shared_ptr是如何自动转换为原始指针的

How is this shared_ptr automatically converted to a raw pointer?

本文关键字:转换 原始 指针 何自动 shared ptr 这个      更新时间:2023-10-16

我现在正在学习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)