我正嘗試在C++中使用唯一標識號爲派生類創建一個通用接口。識別派生類,但標識符不起作用
這是我的代碼看起來像(你至少需要C++ 11編譯):
#include <iostream>
#include <memory>
class Base
{
protected:
int ident;
Base(int newIdent) : ident(newIdent) { }
public:
Base() : ident(0x01) { }
virtual ~Base() { } //needed to make class polymorphic
int getIdent() { return ident; }
};
class Derived : public Base
{
protected:
int answer;
Derived(int newIdent, int newAnswer) : Base(newIdent), answer(newAnswer) { }
public:
Derived(int newAnswer) : Base(0x11), answer(newAnswer) { }
int getAnswer() { return answer; }
};
int main()
{
std::shared_ptr<Base> bPtr = std::make_shared<Derived>(Derived(42));
std::cout << "ident = 0x" << std::hex << bPtr->getIdent() << std::dec << "\n";
if(bPtr->getIdent() & 0xF0 == 1)
{
std::shared_ptr<Derived> dPtr = std::dynamic_pointer_cast<Derived>(bPtr);
std::cout << "answer = " << dPtr->getAnswer() << "\n";
}
return 0;
}
當然,你應該想到的是,計劃產出ident = 0x11
和answer = 42
,但它不,因爲它在ident = 0x11
後面通常存在。我也做了一些檢查有GDB,並在主函數中的關鍵if
條件檢查的拆卸確認問題:
0x0000000000400f46 <+196>: call 0x401496 <std::__shared_ptr<Base, (__gnu_cxx::_Lock_policy)2>::operator->() const>
0x0000000000400f4b <+201>: mov rdi,rax
0x0000000000400f4e <+204>: call 0x4012bc <Base::getIdent()>
0x0000000000400f53 <+209>: mov eax,0x0
0x0000000000400f58 <+214>: test al,al
0x0000000000400f5a <+216>: je 0x400fb7 <main()+309>
當你*0x400f53
突破,RAX很好地保持正確的值(0x11
),但以下指令只是用零覆蓋rax,test
設置零標誌,je
指令跳轉到主函數的末尾,因爲零標誌被設置。這裏發生了什麼?我錯過了什麼或者是編譯器(g++ 4.9.2
與x86_64-linux-gnu
目標)生成錯誤的指令?
'的std :: make_shared(導出(42))'爲什麼多餘的副本? –
定義「它終止」。 –
@LightnessRacesinOrbit它正常存在。 – sigalor