ZLMediaKit/ZLToolKit

static_pointer_cast的使用

feixintianxia opened this issue · 1 comments

想咨询一下:

void TcpServer::start_l(uint16_t port, const std::string &host, uint32_t backlog) {
    //语句A
   weak_ptr<TcpServer> weak_self = std::static_pointer_cast<TcpServer>(shared_from_this());
   ...
   //语句B
   EventPoller::Ptr poller = static_pointer_cast<EventPoller>(executor);
}

参考:
https://en.cppreference.com/w/cpp/memory/shared_ptr/pointer_cast
语句A:
shared_from_this() 返回的是 std::shared_ptr
由基类向派生类转换应该使用std::dynamic_pointer_cast 返回std::shared_ptr

语句B:
同样需要使用std::dynamic_pointer_cast 。
我看了提交记录,最初使用td::dynamic_pointer_cast, 后来才修改为 static_pointer_cast。

为什么呢?