Hen*_*ang 4 c++ c++-standard-library c++11
我现在正在学习enable_shared_from_thisC++ 11; 一个例子让我感到困惑:shared_ptr返回的类型如何shared_from_this()转换为这个原始指针?
#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::Foo\n"; }
~Foo() { std::cout << "Foo::~Foo\n"; }
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;
}
Run Code Online (Sandbox Code Playgroud)
这很std::bind聪明,而不是指针.
如Callable中所述,当调用指向非静态成员函数的指针或指向非静态数据成员的指针时,第一个参数必须是引用或指针(可能包括智能指针,如std :: shared_ptr和std: :unique_ptr)到将访问其成员的对象.
bind 实现,因此它可以接受智能指针代替原始指针.
你可以在glibc ++实现中bindinvoke看到内部调用:
// 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)...
);
}
Run Code Online (Sandbox Code Playgroud)
并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).