我正在学习enable_shared_from_this
现在是 C++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;
}
This is std::bind https://en.cppreference.com/w/cpp/utility/functional/bind是聪明的,而不是指针。
如 Callable 中所述,当调用指向非静态成员函数的指针或指向非静态数据成员的指针时,第一个参数必须是引用或指针(可能包括智能指针,例如 std::shared_ptr 和 std: :unique_ptr) 到将访问其成员的对象。
bind
已实现,因此它可以接受智能指针来代替原始指针。
您可以在glibc++ 实现比bind内部调用invoke https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/include/std/functional#L400:
// 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)...
);
}
And std::invoke https://en.cppreference.com/w/cpp/utility/functional/invoke与智能事物一起工作(指针,参考包装器 https://stackoverflow.com/a/54418456/5470596等)开箱即用:
INVOKE(f, t1, t2, ..., tN)
定义如下:
If f
是指向类的成员函数的指针T
:
- If
std::is_base_of<T, std::decay_t<decltype(t1)>>::value
是真的,那么INVOKE(f, t1, t2, ..., tN)
相当于(t1.*f)(t2, ..., tN)
- If
std::decay_t<decltype(t1)>
是一个专业化std::reference_wrapper
, then INVOKE(f, t1, t2, ..., tN)
相当于(t1.get().*f)(t2, ..., tN)
-
If
t1
不满足前面几项,则INVOKE(f, t1, t2, ..., tN)
相当于((*t1).*f)(t2, ..., tN)
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)