static_pointer_cast的使用
feixintianxia opened this issue · 1 comments
feixintianxia commented
想咨询一下:
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。
为什么呢?
alexliyu7352 commented
static_pointer_cast不在运行时做类型检查, 这里可以确定转换类型, 所以使用static_pointer_cast性能更好.
Mr. Li ***@***.***> 于2023年11月28日周二 00:30写道:
… 想咨询一下:
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。
为什么呢?
—
Reply to this email directly, view it on GitHub
<#195>, or unsubscribe
<https://github.com/notifications/unsubscribe-auth/AF3RPRL7SPR2HLOOTQOWBWTYGS5Z3AVCNFSM6AAAAAA74J7BDCVHI2DSMVQWIX3LMV43ASLTON2WKOZSGAYTENRVGYZTENY>
.
You are receiving this because you are subscribed to this thread.Message
ID: ***@***.***>