2012-01-10 97 views
2

我正在學習Cinder框架。 有一類Texture在此框架下,它可以這樣使用:這個轉換到bool工作如何?

Texture myImage; 
myImage.loadImage(/*...*/); 
if(myImage) 
{ 
    // draw the image. 
} 

我困惑這一點,因爲myImage是一個對象。使用它作爲條件對我來說沒有意義。我預計像myImage.exist();。於是我通過代碼加強,並且事實證明,Texture類有定義的轉換操作符:

public: 
    //@{ 
    //! Emulates shared_ptr-like behavior 
    typedef std::shared_ptr<Obj> Texture::*unspecified_bool_type; 
    // What is this??? 
    operator unspecified_bool_type() const { return (mObj.get() == 0) ? 0 : &Texture::mObj; } 
    void reset() { mObj.reset(); } 
    //@} 

obj是定義爲:

protected:  
    struct Obj { 
     Obj() : mWidth(-1), mHeight(-1), mCleanWidth(-1), mCleanHeight(-1), mInternalFormat(-1), mTextureID(0), mFlipped(false), mDeallocatorFunc(0) {} 
     Obj(int aWidth, int aHeight) : mInternalFormat(-1), mWidth(aWidth), mHeight(aHeight), mCleanWidth(aWidth), mCleanHeight(aHeight), mFlipped(false), mTextureID(0), mDeallocatorFunc(0) {} 
     ~Obj(); 

     mutable GLint mWidth, mHeight, mCleanWidth, mCleanHeight; 
     float   mMaxU, mMaxV; 
     mutable GLint mInternalFormat; 
     GLenum   mTarget; 
     GLuint   mTextureID; 
     bool   mDoNotDispose; 
     bool   mFlipped; 
     void   (*mDeallocatorFunc)(void *refcon); 
     void   *mDeallocatorRefcon;    
    }; 
    std::shared_ptr<Obj>  mObj; 

我知道operator int() const可以implictly改變對象爲int ,但unspecified_bool_type如何工作?當執行if(myImage)時,調試器在operator unspecified_bool_type() const { return (mObj.get() == 0) ? 0 : &Texture::mObj; }處停止。

而且我可能是對這裏的語法有點困惑,這是什麼

typedef std::shared_ptr<Obj> Texture::*unspecified_bool_type; 

是什麼意思?

而且確實

void (*mDeallocatorFunc)(void *refcon); 

在的OBJ意味着mDeallocatorFunc是類的OBJ,函數指針與原型的功能的構件:void xxx(void *)

+1

看起來像一些「安全布爾成語」的咒語... – 2012-01-10 19:26:12

+0

@KerrekSB我想我知道了它,它定義了一個轉換運算符,它可以將'Texture'轉換爲'shared_ptr ',其餘的檢查提供通過'shared_ptr '。但是'typedef std :: shared_ptr Texture :: * unspecified_bool_type;'mean? 'typedef std :: shared_ptr unspecified_bool_type''有什麼區別嗎?我對這種語法感到困惑,尤其是':: *'你能幫助我嗎?非常感謝你。 – shengy 2012-01-10 19:32:58

+0

這件事特別是一個指向成員的指針(它不是一個普通的指針!),但除此之外,我還沒有閱讀足夠的代碼。有很多流行的方法來實現SBI,所以如果你搜索一下,你可能會發現一個與你的代碼非常相似的描述... – 2012-01-10 19:35:06

回答

4

這是the safe bool idiom。它不會簡單地使用operator bool(),因爲隱式轉換可能會導致該運算符出現各種問題。所以相反,它使用可隱式轉換爲bool的類型(如指向成員的指針),這是最不危險的可能。

幸運的是,這種黑客攻擊在C++ 11中不是必需的,因爲我們可以寫explicit operator bool而不是隱式轉換。

+1

相關:[在C++ 11中是否安全布爾成語已過時](http://stackoverflow.com/q/6242768/500104) – Xeo 2012-01-10 23:41:53