2016-05-16 56 views
1

我正嘗試在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 = 0x11answer = 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.2x86_64-linux-gnu目標)生成錯誤的指令?

+1

'的std :: make_shared (導出(42))'爲什麼多餘的副本? –

+0

定義「它終止」。 –

+0

@LightnessRacesinOrbit它正常存在。 – sigalor

回答

5

始終在啓用警告的情況下進行編譯。你的問題是操作問題,即&具有比==較低的優先順序,所以你需要:

if ((bPtr->getIdent() & 0xF0) == 1) 

雖然那麼你對錯誤的東西進行比較,所以你真的

if ((bPtr->getIdent() & 0xF0) == 0x10) 

在這種情況下,你會看到從GCC:

main.cpp:32:32: warning: suggest parentheses around comparison in operand of '&' [-Wparentheses] 
    if(bPtr->getIdent() & 0xF0 == 1) 
          ~~~~~^~~~ 

或本從鐺:

main.cpp:32:25: warning: & has lower precedence than ==; == will be evaluated first [-Wparentheses] 
    if(bPtr->getIdent() & 0xF0 == 1) 
         ^~~~~~~~~~~ 
main.cpp:32:25: note: place parentheses around the '==' expression to silence this warning 
    if(bPtr->getIdent() & 0xF0 == 1) 
         ^
          (  ) 
main.cpp:32:25: note: place parentheses around the & expression to evaluate it first 
    if(bPtr->getIdent() & 0xF0 == 1) 
         ^
     (     ) 
+0

這是一個恥辱鏗鏘使用,誤導「將被評估第一」的術語。 –

+0

http://kera.name/articles/2013/10/nobody-writes-testcases-any-more/ –

+0

@LightnessRacesinOrbit爲什麼你會在博客上有陰影文字... – Barry