一千萬個為什麽

搜索

const :: dynamic_pointer_cast與const指針不起作用?

假設我有兩個類,A和B,其中B是A的子類。

我還有以下功能:

void foo(boost::shared_ptr a)
{
    boost::shared_ptr b = boost::dynamic_pointer_cast(a);//Error !
}

使用gcc編譯給出了以下錯誤:

C:\Boost\include/boost/smart_ptr/shared_ptr.hpp: In constructor 'boost::shared_ptr<  >::shared_ptr(const boost::shared_ptr&, boost::detail::dynamic_cast_tag) [with Y = const A, T = const B]':
C:\Boost\include/boost/smart_ptr/shared_ptr.hpp:522:   instantiated from 'boost::shared_ptr boost::dynamic_pointer_cast(const boost::shared_ptr&) [with T = const B, U = const A]'
src\a.cpp:10:   instantiated from here
C:\Boost\include/boost/smart_ptr/shared_ptr.hpp:259: error: cannot dynamic_cast 'r->boost::shared_ptr::px' (of type 'const class A* const') to type 'const class B*' (source type is not polymorphic)

什麽可能是錯的?

謝謝。

編輯

實際上,我發現了如何避免這種情況,但我不確定。

我的 A 類是空的(因此沒有虛擬析構函數)。如果我添加一個虛擬析構函數,則錯誤消失。但我不明白,為什麽這需要?

最佳答案

dynamic_pointer_cast uses the C++ dynamic_cast internally and dynamic_cast requires your classes to have at least one virtual method. No virtual methods means no vtable and without vtable dynamic_cast would not be able to figure which casts are doable at run-time.

轉載註明原文: const :: dynamic_pointer_cast與const指針不起作用?