gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:33:43 29 4
gpt4 key购买 nike

我现在正在学习 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::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;
}

最佳答案

这是 std::bind 变得聪明,而不是指针。

As described in Callable, when invoking a pointer to non-static member function or pointer to non-static data member, the first argument has to be a reference or pointer (including, possibly, smart pointer such as std::shared_ptr and std::unique_ptr) to an object whose member will be accessed.

bind 已实现,因此它可以接受智能指针来代替原始指针。

glibc++ implementation than bind internally calls 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 可以开箱即用地处理智能事物(指针、reference wrappers 等):

INVOKE(f, t1, t2, ..., tN) is defined as follows:

If f is a pointer to member function of class T:

  • If std::is_base_of<T, std::decay_t<decltype(t1)>>::value is true, then INVOKE(f, t1, t2, ..., tN) is equivalent to (t1.*f)(t2, ..., tN)
  • If std::decay_t<decltype(t1)> is a specialization of std::reference_wrapper, then INVOKE(f, t1, t2, ..., tN) is equivalent to (t1.get().*f)(t2, ..., tN)
  • If t1 does not satisfy the previous items, then INVOKE(f, t1, t2, ..., tN) is equivalent to ((*t1).*f)(t2, ..., tN).

关于c++ - 这个 shared_ptr 是如何自动转换为原始指针的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54417757/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com